[英]how to pass checkbox values in an array to a function using onclick in javascript
how to pass checkbox values in an array to a function using onclick in JavaScript. 如何在JavaScript中使用onclick将数组中的复选框值传递给函数。 following is my html code.
以下是我的html代码。 Note that I don't use form tag.
请注意,我不使用表单标签。 only input tags are used.
仅使用输入标签。
<input id="a"name="a" type="checkbox" value="1" checked="checked" >A</input>
<input id="a"name="a" type="checkbox" value="2" checked="checked" >B</input>
<input id="a"name="a" type="checkbox" value="3" checked="checked" >C</input>
<button onclick="send_query(????)">CLICK</button>
following is my JavaScript function 以下是我的JavaScript函数
function send_query(check) {
var str = "";
for (i = 0; i < check.length; i++) {
if (check[i].checked == true) {
str = str + check[i];
}
console.log(str);
}
You can write a onclick handler for the button, which can create an array of clicked checkbox values and then call the send_query
with the parameter as shown below 您可以为按钮编写一个onclick处理程序,该处理程序可以创建一系列单击复选框值,然后使用以下参数调用
send_query
<button onclick="onclickhandler()">CLICK</button>
then 然后
function onclickhandler() {
var check = $('input[name="a"]:checked').map(function () {
return this.value;
}).get();
console.log(check);
send_query(check)
}
Note: I would also recommend using jQuery to register the click handler instead of using inline onclick
handler . 注意:我还建议使用jQuery注册单击处理程序,而不要使用内联
onclick
处理程序 。
Note: Also ID
of elements must be unique in a document... you have multiple elements with id a
, I'm not seeing you using that id anywhere so you could probably remove it 注意:元素的
ID
在文档中也必须是唯一的...您有多个ID为a
元素,但我在任何地方都看不到使用该ID,因此您可以将其删除
Try this 尝试这个
<form name="searchForm" action="">
<input type="checkbox" name="categorySelect[]" id="1"/>
<input type="checkbox" name="categorySelect[]" id="2" />
<input type="checkbox" name="categorySelect[]" id="3"/>
<input type="button" value="click" onclick="send_query();"/>
</form>
JS JS
function send_query() {
var check = document.getElementsByName('categorySelect[]');
var selectedRows = [];
for (var i = 0, l = check.length; i < l; i++) {
if (check[i].checked) {
selectedRows.push(check[i]);
}
}
alert(selectedRows.length);
}
With pure javascript ( demo ) (tested with Chrome only). 使用纯javascript( demo )(仅通过Chrome测试)。
HTML : HTML:
<button onclick="send_query(document.getElementsByTagName('input'))">
Javascript : Javascript:
function send_query(check) {
var values = [];
for (i = 0; i < check.length; i++) {
if (check[i].checked == true) {
values.push(check[i].value);
}
}
console.log(values.join());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.