仅从 Javascript 中的 getElementsByName() 获取选中的元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17422390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get only checked element from getElementsByName() in Javascript?
提问by pynovice
I have a HTML like this:
我有一个这样的 HTML:
<input type="checkbox" name="choice_shrd_with_me" id="choice{{ forloop.counter }}" value="{{ choice.file_name }}" />
I am trying to get only the checked elements in array like this in Javascript:
我试图在 Javascript 中像这样只获取数组中已检查的元素:
var choices = [];
for (var i=0;i<document.getElementsByName('choice_shrd_with_me').length;i++){
choices.push(document.getElementsByName("choice_shrd_with_me")[i].value);
}
The above gets all the values whether the checkbox is checked or not. I want to get only the values on which checkbox is checked. How can I do that?
无论是否选中复选框,上述内容都会获取所有值。我只想获取选中复选框的值。我怎样才能做到这一点?
回答by Sirko
Just filter for the elements which are checked:
只需过滤已检查的元素:
var choices = [];
var els = document.getElementsByName('choice_shrd_with_me');
for (var i=0;i<els.length;i++){
if ( els[i].checked ) {
choices.push(els[i].value);
}
}
回答by Kevin Bowersox
For IE < 9
对于 IE < 9
function getCheckedByName(name){
var chks = document.getElementsByName(name);
var results = [];
for(var i = 0; i < chks.length; i++){
chks[i].checked ? results.push(chks[i]):"";
}
return results;
}
For Modern Browsers
对于现代浏览器
function getModernCheckedByName(name){
return Array.prototype.slice.call(document.getElementsByName(name)).filter(function(e){
return e.checked;
});
}
Working Example
工作示例