2
<input type="radio" id="radio1" name="rb1" value="no"> No
<input type="radio" id="radio2" name="rb1" value="yes"> Yes

when I say this alert("Test =="+$('#radio1').attr('checked')); I expect false because it's not checked but it returns undefined.

What is the correct statement? Why am I getting undefined?

1
  • 1
    if it's not checked, there is no 'checked' attribute, thus undefined
    – Homer
    Commented Apr 8, 2011 at 15:40

3 Answers 3

5

This post explains your exact problem: http://forum.jquery.com/topic/checking-if-certain-radiobutton-is-checked

i.e. you need to use this: alert($('#radio1').is(':checked'));

1
  • to sum up: if it's checked, it has a 'checked' attribute. if it's not checked, there is no 'checked' attribute, thus undefined
    – Homer
    Commented Apr 8, 2011 at 15:39
2

You get undefined because the checked attribute only exists when the element is selected.

You can get the value of the selected element like this:

$('input[name=rb1]:checked').val()

You can check if a specific element is checked in several way, for example:

if ($('#radio1:checked').length) ...

or:

if ($('#radio1').is(':checked')) ...
1
// checked value
var value = $("input[@name=rb1]:checked").val();

alert("Test == " + $('#radio1').val() == value );

Not the answer you're looking for? Browse other questions tagged or ask your own question.