简体   繁体   中英

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. following is my html code. 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

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

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

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

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

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

HTML :

<button onclick="send_query(document.getElementsByTagName('input'))">

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM