2

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();
        }); 
}); 
1
  • do you really need .each method here?? because when you tick as example one of the checkbox, it will trigger this code. And you can use push function to add the value and splice it using .splice Commented Mar 26, 2015 at 3:33

4 Answers 4

4

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();
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this...I didn't know about the map()...so I have learned something!
0

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

Comments

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

Comments

-1

This sort of worked, but map() is more accurate:

          if($(this).is(':checked')) {
    departments.push($(this).val());
  } else {
    departments.pop($(this).val());
  }

1 Comment

The pop() method removes the last element from an array and returns that element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.