Attach event listener through javascript to radio button

前端 未结 5 804
春和景丽
春和景丽 2020-12-03 08:13

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

5条回答
  •  醉酒成梦
    2020-12-03 08:59

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

提交回复
热议问题