Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Radio Buttons, Groups and JQuery

4.89/5 (7 votes)
18 Jul 2011CPOL 59.6K  
Simple implementation for determining which radio buttons are selected using Jquery
Recently I was working on a small tool/article and was trying to work out the simplest way of handling RadioButtons, Radio Button Groups and then determining which is selected using JQuery.

This is the implementation I came up with;

1) Add your radio buttons to the page and assign them their unique ID as usual
2) For each radio button in the group, set the NAME property to the SAME value
3) Assign a unique value to each radio button VALUE property

What you will end up with is something like the following (radio button 1 is default selected);

HTML
<input type="radio" id="radio1" name="RadioGroup1" value="1" checked="true"/>
<input type="radio" id="radio2" name="RadioGroup1" value="2" />
<input type="radio" id="radio3" name="RadioGroup1" value="3" />


By assigning the same NAME to each radio button means that if radio2 is selected, then radio1 and radio3 are deselected. If you don't set the same name, then multiple radio buttons can become selected.

Then to determine which radio button is selected using JQuery you can use the following code;
JavaScript
var value = $("input[name=RadioGroup1]:checked").val();

alert("The user selected; " + value);


The JQuery statement, looks for an input element which has the name property "RadioGroup1" and is checked, then returns its value.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)