0

I have two radio buttons:

<table border="0" width="500"> 
    <tr><td><?php echo form_label('Register with a Club', 'club'); ?>&nbsp;<?php echo form_radio('individual', 'club', '', 'id=club'); ?></td><td><?php echo form_label('Register as an Independent', 'independent'); ?>&nbsp;<?php echo form_radio('individual', 'independent', '', 'id=independent'); ?></td></tr>
    </table>

this spits out:

<table border="0" width="500"> 

    <tr><td><label for="club">Register with a Club</label>&nbsp;<input type="radio" name="individual" value="club" id=club /></td><td><label for="independent">Register as an Independent</label>&nbsp;<input type="radio" name="individual" value="independent" id=independent /></td></tr>
    </table>

I am trying to alert out the value of the of the radio button group....I have tried...

<script type="text/javascript">
$(function(){
 alert($("input[name='individual']").val());
    });
</script>

but it returns only 'club' once, why is not alerting 'independent'?

4

2 回答 2

2

You'll need to alert the value of the radio button that is actually checked, otherwise it will just return the value of the first element in the selection, which is "club", always :

$(function(){ 
    $("input[name='individual']").on('change', function() {
        alert($("input[name='individual']:checked").val());
    });
});
    ​

FIDDLE

If you need both values (or more if there are more radio buttons in the group), you have to iterate over them:

$(function(){ 
    var values=[];
    $.each($('input[name="individual"]'), function(i,elm) {
        values.push(elm.value);
    });
    alert(values.join(', '));
});

FIDDLE

于 2012-11-07T02:03:47.840 回答
1

Your code will only get the value of the first element. If you get the length you'll in fact see that it grabs all inputs:

$("input[name='individual']").length

If you want to alert all values you need to loop:

$("input[name='individual']").each(function() { alert( this.value ); });

If what you want is to get the value of current checked input:

$("input[name='individual']:checked").val()
于 2012-11-07T02:03:01.340 回答