Finding the value of a radio button

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
	</form>

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;
					break;
				}
			}
		}
 
	</script>

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
	</form>
Did you like this? If so, please
tell a friend
about it, and subscribe to the blog RSS feed.

Share/Save/Bookmark

If you enjoyed this post, make sure you subscribe to my RSS feed!



Related Posts:
  • JavaScript fading effect


  • 5 Responses to “Finding the value of a radio button”  

    1. 1 ye

      very nice! thank you so much big help!muah!

    2. 2 Arun

      Thank you so much for the post. I was struggling to find the value of selected radio button. In my case since the radio button was dynamically generated some times there will be only one radio button and my javascript code was not working. Thanks for the simple fix.

    3. 3 Manu

      Thanks a lot.Thank you for such a simple fix. I was struggling to find the value when there is only one radio button in a form

    4. 4 Kathy

      This was great! Thanks for the help.

    5. 5 X

      Thanks

    Leave a Reply