Featured Posts

Integrating GlassFish Application server with Apache... A typical production topology for GlassFish will be a front ending GlassFish with Apache for serving the static files. To integrate GlassFish Application Server with Apache web server follow the below...

Readmore

Some Java, JEE and WebSphere stuffs Rss

Finding the value of a radio button

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

6

1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 4.33 out of 5)
2,453 views

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>
  • Share/Bookmark

Read More

Comments (6)

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

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.

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

This was great! Thanks for the help.

Thanks

thank you very much
It is very helpful

Write a comment