如何使用纯 JavaScript(不使用 JS 框架)从表单中选择所有复选框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7791507/
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
How can I select all checkboxes from a form using pure JavaScript (without JS frameworks)?
提问by user737065
I have question, how write function to select all chceckbox on form, when all checkbox Id start from some const. string, using pure java script (without jquery and other frameworks) ? I know how do it using each function from JQuery, but I dont have any idea hwo do it in pure JS.My form ex.
我有一个问题,当所有复选框 Id 从某个常量开始时,如何编写函数来选择表单上的所有复选框。字符串,使用纯 java 脚本(没有 jquery 和其他框架)?我知道如何使用 JQuery 中的每个函数,但我不知道如何在纯 JS.My 表单中执行此操作。
<form id="myId" name="myForm">
<input type="checkbox" id="lang_1" value="de"/> DE
<input type="checkbox" id="lang_2" value="us"/> US
<input type="checkbox" id="lang_3" value="ru"/> RU
<input type="button" onclick="Select();" value="Select all"/>
</form>
采纳答案by gregseth
In your case:
在你的情况下:
for (i = 1; i<3; i++) {
document.getElementById('lang_'+i).checked = true;
}
回答by James Allardice
You could use getElementsByTagName
to get all the input
elements:
您可以使用getElementsByTagName
来获取所有input
元素:
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type == "checkbox") {
inputs[i].checked = true;
}
}
Here's an exampleof that. If you only care about newer browsers, you could use querySelectorAll
:
这是一个例子。如果您只关心较新的浏览器,则可以使用querySelectorAll
:
var inputs = document.querySelectorAll("input[type='checkbox']");
for(var i = 0; i < inputs.length; i++) {
inputs[i].checked = true;
}
And an exampleof that one. As an aside, you mentioned in your question that when using jQuery you could do this using each
. You don't need to use each
, as most jQuery methods operate on all elements in the matched set, so you can do it in just one line:
还有一个例子。顺便说一句,您在问题中提到,在使用 jQuery 时,您可以使用each
. 您不需要使用each
,因为大多数 jQuery 方法对匹配集合中的所有元素进行操作,因此您只需一行即可完成:
$("input[type='checkbox']").prop("checked", true);