Dave
Dave

Reputation: 1076

Selecting values of two radio buttons jQuery

I have the following HTML:

<div class="row1">
    <input type="radio" name="group1" value="0" checked="checked"/>Zero
    <input type="radio" name="group1" value="1" />One
</div>

<div class="row2">
    <input type="radio" name="group2" value="0" checked="checked" />Zero
    <input type="radio" name="group2" value="1" />One
</div>

Along with the following jQuery code:

$(document).ready(function() {
    var val1 = "";
    var val2 = "";

    $('input[name="group1"],input[name="group2"]').change(function() {
        val1 = $('input[name="group1"]').val();
        val2 = $('input[name="group2"]').val();
        alert(val1 + " : " + val2);
    });

});

Now, my expected result is that when one of the radio buttons is changed, it gets the selected values of both radio buttons and displays them in an alert box.

As you can see using my jsFiddle here: http://jsfiddle.net/2whkp/ The result is always 0:0. I have a feeling this may be due to it always just getting the first radio button by that name. If that is the case however, how would I work around this?

Thanks in advance,

Dave

Upvotes: 1

Views: 361

Answers (3)

roselan
roselan

Reputation: 3775

$(document).ready(function() {
    var val1 = "";
    var val2 = "";

    $('input:radio').change(function() {
        val1 = $('input:radio[name="group1"]:checked').val();
        val2 = $('input:radio[name="group2"]:checked').val();
        alert(val1 + " : " + val2);
    });

});

Upvotes: 1

Evgeniy Kirov
Evgeniy Kirov

Reputation: 534

Yes, you're right, that's the value of first input in the group. Just use $('input[name="group1"]:checked') instead of $('input[name="group1"]')

Upvotes: 0

Malevolence
Malevolence

Reputation: 1857

Add the :checked filter to your selector and it will work. e.g.

val1 = $('input[name="group1"]:checked').val();
val2 = $('input[name="group2"]:checked').val();

Upvotes: 5

Related Questions