Get the value of a radio button in JavaScript

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;
}

10 thoughts on “Get the value of a radio button in JavaScript

  1. hi
    this is very very nice example to get id of the radio …..
    i appriceate ur knowledge…
    thank u!

  2. Hey this is an awesome method. It really works. Appreciate your knowledge. Thanks !!

Comments are closed.