How to work with radio buttons and checkboxes

Getting and setting a form element's value is not usually what we want when we have checkboxes or radio buttons. Rather, we want the value of the selected/checked item. jQuery has a selector filter to help with this called :checked. If we had 10 radio buttons, each of which had a class of "group1", we can find the selected itme with this:

$(".group1:checked").val();

Remembering that our selector can reference more than one item, and that a checkbox can have more than one item checked, we run into problems. In this case we can make use of the .each() method to build that string.

var result = "";
$(".mycheckboxes").each( function () {
result = result + $(this).val() + ", ";
});
//
alert(result);

If we need to set the value of a checkbox or radio button, then we need to a way to reference the desired item. This could be done by giving that item an ID value when creating the page, or by using one of the selector filters. If we wanted to change the fourth check box to have a value of "Item Four", we could do this:

. . .
<input type="checkbox" id="box4" name="box4" value="4">
. . .
$("#box4").val("ItemFour");
OR
$("input:eq(3)").val("ItemFour");
// Note 1: Assuming the inputs on the page are only checkboxes
// Note 2: Remember that our position is zero based

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

val(val) fails in demo for radio buttons

why does this jquery example for val(val) of radio buttons not work ?

http://docs.jquery.com/Attributes/val

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.