admin管理员组

文章数量:1301533

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 appreciated.

Thanks

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 appreciated.

Thanks

Share edited Jun 1, 2011 at 9:45 psoares 4,8837 gold badges43 silver badges56 bronze badges asked Jun 1, 2011 at 9:35 RajeshRajesh 311 gold badge1 silver badge4 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 3

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.

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()

本文标签: javascriptaddEventListener for Radio buttons with same idStack Overflow