0
<input type="radio" name="group2" value="Water"> Water<br>
<input type="radio" name="group2" value="Beer"> Beer<br>
<input type="radio" name="group2" value="Wine" checked> Tee

    <span id="check" >check</span>

And jQuery:

function check()
{
    alert($('input[name=group2]').val());
}
$('#check').click(function(){
    check();
});
$('input[name=group2]').change(function(){
    check()
})

Live: http://jsfiddle.net/j9cj5/

Why this always show me Water? How can i check value of these radio buttons? I would like check this if i change this value and if i click on check.

4

3 回答 3

5

The selector $('input[name=group2]') will select all the elements with that name, and val() returns only the value for the first element in the collection, so that's always Water. You have to target just the checked radio :

function check() {
    alert( $('input[name=group2]:checked').val());
}

FIDDLE

于 2013-06-15T11:36:11.800 回答
4

Replace $('input[name=group2]') with $('input[name=group2]:checked') :)

Demo: http://jsfiddle.net/hungerpain/j9cj5/2/

The reason this happens is because $('input[name=group2]') will generate an array of all your radio buttons and thus will give only the first element (which happens by default). So get the selected element, you must use the :checked pseudo selector.

于 2013-06-15T11:35:26.430 回答
1

Try like this

function check(val) {
     alert(val);
}
$('input[name=group2]').change(function(){
    check($(this).val());
});

This is working FIDDLE

于 2013-06-15T11:35:55.807 回答