简体   繁体   中英

Compare the values of array in javascript

I have two checkboxes, A and B, and when either of them is clicked the event should be triggered. I need to keep track of the checked values in an array.

Possible Values.

[eA,eB] -> if both are checked.
[]      -> if A and B are unchecked.
[eA]    -> if A is checked and also if B is unchecked.
[eB]    -> if B is checked and also if A is unchecked.

I tried some thing like this,

var all = new Array();

getValues = function(e) {
    for (i = 0; i < e.length; i++) {
        all[i] = e[i];
        if (e[i] == "eB") {
            refreshFlag = true;
        }
    }

    if (e.length == 0) {
        //need to check whether eB was checked before and set the flag
    }

    if (e.length == 1) {
        //need to check whether eB was checked before and set the flag
    }
}

How can I do this?

I included jQuery but here is an example of what you would need to do:

 $(document).ready(function() { var outputArr = []; $('input[type="checkbox"]').click(function(e) { var val = $(this).val(); var index = outputArr.indexOf(val); if (index === -1) { outputArr.push(val); } else { outputArr.splice(index, 1); } $('#output').val(JSON.stringify(outputArr)); }); }); 
 <!DOCTYPE html> <html> <head> <style>label { display: block; }</style> <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script> </head> <body> <form id="form"> <label><input type="checkbox" value="eA" /> Checkbox A</label> <label><input type="checkbox" value="eB" /> Checkbox B</label> </form> <textarea id="output" disabled>[]</textarea> </body> </html> 

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