简体   繁体   中英

get value of checked checkbox list in array in jQuery

I have list of checkboxes that has all checkbox pre-checked when page load.

Firstly, I want to read all checkboxes (checked) value and store in global array.

Later, whenever any checkbox is clicked by user (un-checked / checked), I want to update the array with values of only checked checkboxes.

All this i want to do in jQuery.

thanks

<input type="checkbox" value="somevalue1" class="chk">
<input type="checkbox" value="somevalue2" class="chk">
<input type="checkbox" value="somevalue3" class="chk">
<input type="checkbox" value="somevalue4" class="chk">
<input type="checkbox" value="somevalue5" class="chk">
<script>
var someGlobalArray = new Array;

$(".chk").click(function() {
    someGlobalArray=[];
    $('.chk:checked').each(function() {
        someGlobalArray.push($(this).val());
    });
    console.log(someGlobalArray);
});
</script>

Did you mean something like this?

var arrCheckboxes;
var checkboxSelector = "input[type='checkbox']";
$("body").delegate(checkboxSelector , "click", function(){
    arrCheckboxes = $(checkboxSelector).map(function() {
        return this.checked;
    }).get();
});

(Maybe you should change the $("body") to a more precise container)

If you want an array with objects with name (...or id or maybe the element)... you can do something like this:

var arrCheckboxes;
var checkboxSelector = "input[type='checkbox']";
$("body").delegate(checkboxSelector , "change", function(){
    arrCheckboxes = $(checkboxSelector).map(function() {
        return { name: this.name, val: this.checked };
    }).get();
});

I assume that you want is the name or id of the checked items, since checkbox values are boolean?

var checked = {};
$(':input[type="checkbox"]').each(function() {
    var name= this.name;
    var val = this.checked;
    if (val) {
        checked[name] = val;
    }
}).on('change', function() {
    var name = this.name;
    var val = this.checked;
    if (val) {
        checked[name] = val;
    } else {
        delete checked[name];
    }
});

The object checked will then contain keys , and only those corresponding to checked items will appear in that object.

Working demo at http://jsfiddle.net/tFYPF/

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