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

Read More

Comments

13 comments posted onFinding the value of a radio button

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

  2. 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. 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. This was great! Thanks for the help.

  5. Thanks

  6. thank you very much
    It is very helpful

  7. nice one.. very useful

  8. why its not working in ie?

  9. good

  10. Thank u, this is really helping me out ^^

  11. thnx

  12. Thanks… its really help full for me…Thanks again..

  13. Thanks… its really help full

Post a Comment