开发者

addEventListener for Radio buttons with same id

Is it possible to add events using addEventListener to multiple radio buttons with same id ?

<input id="radId" type="radio" value="0" name="radioname">No
<input id="radId" type="radio" value="1" name="radioname">Yes

I tried to attach event using document.getelementByID BUT it always picks the first radio button.

Is there a way around this, any help would be highly appreci开发者_Go百科ated.

Thanks


As others said, an ID has to be unique. You could get elements with getElementsByName (note that there are some issues) and iterate over them:

var handler = function() {
    //...
};

var radios = document.getElementsByName('radioname');

for(var i = radios.length; i--; ) {
    radios[i].onclick = handler;
}

Also note that addEventListener does not exist in < IE8, there you have to use attachEvent. I suggest to read the excellent articles about event handling on quirksmode.org.


document.getElementsByName('radioname').forEach(function(e) {
    e.addEventListener("click", function() {
        alert(e.value);
    });
});


No, that is invalid. ID must be unique.

Well, you can if you can select the elements some other way - by class, tag, childNode, etc.


 var radiobuttonlist= document.querySelectorAll('#radId');
var radioButtonItems = [].slice.call(radiobuttonlist);

    radioButtonItems.forEach(function (item, idx) {
    item.addEventListener('change',YourFunction);});


Create array of the radio type elements and use forEach!

<input type="radio" value="0" name="radioname">No
<input type="radio" value="1" name="radioname">Yes

<script>
//Load entire html document
window.addEventListener("load", function(){
   //Array elements radio
   var radioOption = [document.getElementsByName('radioname')[0],document.getElementsByName('radioname')[1]];
   //Use forEach
   radioOption.forEach(function(e) {
       e.addEventListener("click", function() {             
       alert(e.value);
       });
    });
});
</script>


dont use the same id for 2 elemetns, use classes. and then you can use something like this

document.getElementsByClassName("whateverclass").onclick=function()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜