John Dyer

Technology and web development in curly bracket languages {Javascript, C#, ActionScript}

Get the value of a radio button in JavaScript

by John Dyer 23. August 2006 00:02
I regularly use the prototype javascript library in JavaScript development (in fact, FreeTextBox4 will use it). But I've found that the $F() function doesn't work like I expect it to with radio buttons. $F() will return null if a radio is not checked and the value if it is checked. What I want it to do is figure out the value of the currently selected radio in the radio group (all with the same name). Since prototype doesn't do it, I decided to write one to do it. It will return null if none of the radios are checked and it works using either the ID of one of the radios or the name of the group. Here it is

function getRadioValue(idOrName) {
	var value = null;
	var element = document.getElementById(idOrName);
	var radioGroupName = null;  
	
	// if null, then the id must be the radio group name
	if (element == null) {
		radioGroupName = idOrName;
	} else {
		radioGroupName = element.name;     
	}
	if (radioGroupName == null) {
		return null;
	}
	var radios = document.getElementsByTagName('input');
	for (var i=0; i<radios.length; i++) {
		var input = radios[ i ];    
		if (input.type == 'radio' && input.name == radioGroupName && input.checked) {                          
			value = input.value;
			break;
		}
	}
	return value;
}

Comments

8/21/2007 10:34:07 PM # Klok Klok | Reply
Just wanted to say: Thanks for the code.
6/1/2008 11:39:19 PM # J M J M Canada | Reply
Thanks a lot, that code really helped!
8/28/2008 11:57:41 AM # Amol kagde Amol kagde India | Reply
hi

this is very very nice example to get id of the radio .....
i appriceate ur knowledge...

thank u!
8/29/2008 7:04:47 PM # Raju Raju India | Reply
Thanks for the code buddy Smile
9/1/2008 4:52:53 PM # Mike Mike Finland | Reply
Hiya, just wanted you to know I found a neat little solution which worked perfectly for me.

stereointeractive.com/.../

The snippet is as follows:
$$('input:checked[type="radio"][name="my_radio_group"]').pluck('value');
9/1/2008 8:44:32 PM # John Dyer John Dyer United States | Reply
@Mike, that's great! How JavaScript usage has evolved in the 2 years since I posted this...
John Dyer's last post: feedproxy.google.com/.../post.aspx" rel="nofollow">Simple Cross-Browser HTML5 video with a single H.264 file and fallback options
6/9/2010 12:17:10 AM # Andrés Andrés Chile | Reply
Thank's John,
great function.

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Web Statistics