Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 227
  • Last Modified:

javascript check for radio buttons

we have a javascript being passed dynamically into a webform, we insert data into the webform, but we need to check and select a radio button, how can we do this ?

 var formContent = {
"0":"905",
"9":"",
"10":"test123"
}

here is the code inserting the form values


var form = document.getElementById('Form1'); 

	for (var o in formContent) 
	{
		form.elements[o].value=formContent[o];
	}
                

Open in new window

0
goodluck11
Asked:
goodluck11
1 Solution
 
micropc1Commented:
Here are a couple of custom functions I've written to do this...

setRadioValue = function (radioName, newValue) {
	var radioObj = document.getElementsByName(radioName);
	if(radioObj != null) {
		var radioLength = radioObj.length;

		if(radioLength == undefined) {
			radioObj.checked = (radioObj.value == newValue.toString());
		} else {
			for(var i = 0; i < radioLength; i++) {
				radioObj[i].checked = false;
				if(radioObj[i].value == newValue.toString()) {
					radioObj[i].checked = true;
				}
			}
		}
	}
}


getRadioValue = function (radioName) {
	var myRadios = document.getElementsByName(radioName);
	var retVal = '';
	
	for (var i = 0; i < myRadios.length; i++) {
		if (myRadios[i].checked == true) {
			retVal = myRadios[i].value;
		}
	} 
	
	return retVal;
}

Open in new window


You would use them like this....

Test1 <input type="radio" name="t" id="t" value="test1">
Test1 <input type="radio" name="t" id="t" value="test2">
Test1 <input type="radio" name="t" id="t" value="test3">

<input type="button" onclick="alert (getRadioValue('t'));" value="a">
<input type="button" onclick="setRadioValue('t', 'test2');" value="b">

Open in new window

0
 
Amar BardoliwalaCommented:
Hello goodluck1,

you can try following

var type = form.elements[o].type

if(type=="checkbox")
{
   form.elements[o].checked = formContent[o];
}

Open in new window


Hope this will help you.

Thank You.

Amar Bardoliwala
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now