Reputation: 4304
The following code adds checkbox values to an array when checkboxes are checked. How can I change this so that a checkbox's value is removed from the array when a checkbox is unchecked?
var departments = [];
$("input[name='department_pk[]']").change(function() {
$("input[name='department_pk[]']:checked").each(function(i){
departments[i] = $(this).val();
});
});
Upvotes: 2
Views: 3167
Reputation: 4304
This sort of worked, but map() is more accurate:
if($(this).is(':checked')) {
departments.push($(this).val());
} else {
departments.pop($(this).val());
}
Upvotes: -1
Reputation: 129
check this..
var departments = [];
$("input[name='department_pk[]']").change(function() {
$("input[name='department_pk[]']").each(function(i){
if(jQuery(this).is(":checked")) {
departments[i] = $(this).val();
} else {
departments[i] = 0;
}
});
});
Upvotes: 0
Reputation: 388316
The problem is you are not removing the previously selected items from the array. Assume you have selected 5 items now in the array you have data for indexes 0 to 4, then you are unselecting 2 items now your each loop will reset the indexes 0 to 2 but the indexes 3 and 4 is still present in the array. that is the problem.
A better solution will be is to create a fresh array using .map()
var departments = [];
$("input[name='department_pk[]']").change(function () {
departments = $("input[name='department_pk[]']:checked").map(function (i) {
return $(this).val();
}).get();
});
Upvotes: 4
Reputation: 119
I would clear the array first before you add new elements to it.
var departments = [];
$("input[name='department_pk[]']").change(function() {
departments = [];
$("input[name='department_pk[]']:checked").each(function(i){
departments[i] = $(this).val();
});
});
Upvotes: 0