Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
144
rated 0 times [  151] [ 7]  / answers: 1 / hits: 113616  / 13 Years ago, thu, january 19, 2012, 12:00:00

I have several radio buttons with the same name. Like this:



<form name=formA>
<input type=radio name=myradio value=A/>
<input type=radio name=myradio value=B/>
<input type=radio name=myradio value=C/>
<input type=radio name=myradio value=D/>
</form>


Now I have to add event listener through javascript to all the radio buttons. If the below pseudocode is wrong, then please tell me how to do it-



var radios = document.forms[formA].elements[myradio];
for(radio in radios) {
radio.onclick = function() {
alert(radio.value);
}
}

More From » html

 Answers
70

For in loops in JavaScript return the keys, not the values. To get the for in loop to work, assuming you haven't added custom properties to your array, you'd do:



for(radio in radios) {
radios[radio].onclick = function() {
alert(this.value);
}
}


But you should always loop an array with a regular for loop to avoid accidentally including custom-added enumerable properties:



var radios = document.forms[formA].elements[myradio];
for(var i = 0, max = radios.length; i < max; i++) {
radios[i].onclick = function() {
alert(this.value);
}
}

[#87926] Wednesday, January 18, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
briarc

Total Points: 402
Total Questions: 85
Total Answers: 114

Location: El Salvador
Member since Sun, Sep 12, 2021
3 Years ago
;