Pergunta

If I have some radio buttons:

<input type="radio" name="test" value="apple"> Apple<br/>
<input type="radio" name="test" value="banana" CHECKED> Banana<br/>
<input type="radio" name="test" value="carrot"> Carrot<br/>

and I then define the radio group in jQuery with

var test = $('input:radio[name="test"]')


How can I get the value of the checked element based on the variable test without re-writing

var test_val = $('input:radio[name="test"]:checked').val();

I've tried both

$(test):checked.val();
test:checked.val();

And as part of a change function I've also tried this:

$(test).change(function() {
    if ($(this):checked.val() == 'no') {
        $('#featured').stop().fadeOut();
    } else if ($(this):checked.val() == 'yes') {
        $('#featured').stop().fadeIn();
    }
});

Just wondering if this is possible or if I have to re-write out the full input selector to get the value.

P.S.
If IE8 doesn't support the :checked selector, what can I use instead?

Foi útil?

Solução

You can use .filter()help:

test.filter('input:checked')

.filter() does also support a callback:

test.filter(function() {
    return this.name === 'test' && this.checked
});

I wasn't aware that the :checked selector does not work with IE8. If that is true, the latter example should work (accessing the node expando directly)

Outras dicas

You are trying to mix "CSS syntax" with JavaScript syntax. That won't work.

You can use jQuery's filter() method to limit the elements selected with a previous jQuery query:

var test = $('input:radio[name="test"]')

var test_val = test.filter(":checked").val();

try this...

$(test).change(function() {
 if ($(this).is(':checked').val() == 'no'){
   $('#featured').stop().fadeOut();
 } else if ($(this).is(':checked').val() == 'yes'){
  $('#featured').stop().fadeIn();
 }
});

Startibg from var test, you can use the .filter() function, as shown in this jsFiddle

var test = $('input:radio[name="test"]');
alert(test.filter(':checked').val());
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top