Setting a specific Radio Button within a Radio Group


I have come accross this numerous times… display some radio buttons and cant remember how to get set a specific radio button within a group. In this post I will show you how you can set the value as well as give you the html and javascript to which you can use as you see fit.

View Example


WordPress does not allow code demonstrations on their website so I had to create a separate page with the Demo

Here is how this works. First lets look at the html code.

The Radio Buttons


<input type="radio" name="radioGroup" value="1st Button">1st Button

<input type="radio" name="radioGroup" value="2nd Button">2nd Button

<input type="radio" name="radioGroup" value="3rd Button">3rd Button

The Button selectors


<input type="button" value="Select 1st Button" onclick="javascript:setCheckedValue('1st Button');">

<input type="button" value="Select 2nd Button" onclick="javascript:setCheckedValue('2nd Button');">

<input type="button" value="Select 3rd Button" onclick="javascript:setCheckedValue('3rd Button');">



The Javascript

function setCheckedValue(selectedValue) {

var radioButtons = document.radioForm.radioGroup;
for(var i = 0; i < radioButtons.length; i++){ if(radioButtons[i].value == selectedValue.toString()){ radioButtons[i].checked = true; } } } [/sourcecode] Ive had to use this many times. Recently I needed to set a radio button value depending on data that was being sent to the page. By calling the setCheckedValue(selectedValue) during the page load, I was able to set a specific radio button.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s