Lee
Lee

Reputation: 1280

jquery radio buttons not switching?

I am confused about this code its self explanatory what its supposed to do but it doesn't do it

<input  name="property" type="radio" checked value="1" />Station Masters House
<input  name="property" type="radio" value="2" />Railway Carriage

<br><br>
<div id="fillin">press</div>

$("#fillin").click(function() {    
        if ($('input[name=property]').val() == "1")
        {

            alert($('input[name=property]').val());

        } else if ($('input[name=property]').val() == "2") {

            alert($('input[name=property]').val());
        }


    });

example here

http://jsfiddle.net/BFf5H/40/

Upvotes: 2

Views: 228

Answers (2)

Sean Vieira
Sean Vieira

Reputation: 160043

input[name=property].length === 2 ... therefore, .val() won't work. (.val pulls the value of the first element in the DOM that it finds that matches the requested selector, except in the case of a <select multiple> element.)

Try input[name=property]:checked instead.

$("#fillin").click(function() {    
    if ($('input[name=property]:checked').val() == "1")
    {

        alert($('input[name=property]:checked').val());

    } else if ($('input[name=property]:checked').val() == "2") {

        alert($('input[name=property]:checked').val());
    }


});

Better yet, cache the things you need, so you are only hitting the DOM (or in this case, jQuery's cache) once:

$("#fillin").click(function() {
   var val = $('input[name=property]:checked').val();
    if ( val == "1") {
        alert(val);
    } else if (val == "2") {
        alert(val);
    }
});

Upvotes: 4

Amin Eshaq
Amin Eshaq

Reputation: 4024

you should do

if ($('input[name=property]:checked').val() == "1")

Upvotes: 1

Related Questions