• Entries (RSS)
  • Comments (RSS)

Finding the value of a radio button

Posted by | Posted in JavaScript | Posted on 08-02-2008

Tagged Under :

In order to get the value of a radio button using JavaScript, we need to loop through all the radio buttons in that set and then find out the value of the radio button which is checked.

For eg:

<form name="frmRadio" method="post">
<input name="choice" value="1" type="radio" />1 
<input name="choice" value="2" type="radio" />2 
<input name="choice" value="3" type="radio" />3 
<input name="choice" value="4" type="radio" />4

To get the selected choice we need to use the following code.

	<script language="JavaScript">
		function getRadioValue() {
			for (index=0; index < document.frmRadio.choice.length; index++) {
				if (document.frmRadio.choice[index].checked) {
					var radioValue = document.frmRadio.choice[index].value;

But the same code wouldn’t work when there is only one radio button. When there are two elements with the same name HTML would treat it as an array, but when there is only one radio button, it wouldn’t be an array and hence the above code wouldn’t work.
This problem comes when we generate the radio buttons dynamically as we don’t know the number of options present at design time. To solve this issue we can have a nice workaround. Just add one hidden element with the same name inside the form. We are done
For eg:

<form name="frmRadio">
<input name="choice" value="-1" type="hidden" />
<input name="choice" value="1" type="radio" />1


Read More

Post a Comment