Getting and Setting the Selected Option in a Radio Group

if ($("#maleRB").is(":checked)){   $("#maleRB").removeAttr("checked"); else{   $("#maleRB").attr("checked"); } var genderGroup = $("input[name=gender]"); var checkedGender = genderGroup.filter(":checked"); var selectedGender = checkedGender.val();

Radio inputs are almost always used in groups. The value of a radio input that a group represents is not boolean. Instead, it is the value attribute of the currently selected element. For example, the value of the following radio button group is either "male" or "female":

<input id="maleRB" type="radio" name="gender" value="male"> <label for="maleRB">Male</label> <input id="femaleRB" ...

Get jQuery and JavaScript Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.