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 badges6 Answers
Reset to default 3As 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
版权声明:本文标题:javascript - addEventListener for Radio buttons with same id - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741676445a2391907.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论