IlludiumPu36
IlludiumPu36

Reputation: 4304

Adding and removing values from array by checking and unchecking checkboxes

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

Answers (4)

IlludiumPu36
IlludiumPu36

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

Vinay S Jain
Vinay S Jain

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

Arun P Johny
Arun P Johny

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

Alex Zai
Alex Zai

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

Related Questions