1

I'd like to push checked checkboxes values into an array, but I'm having some issue because each time I try to add it into the array it stays empty, I am probably doing something wrong but can't figure out what.

http://jsfiddle.net/fx7su2rp/689/

HTML :

<input name="checkbox" value="1" type="checkbox" />
<input name="checkbox" value="2" type="checkbox" />
<input name="checkbox" value="3" type="checkbox" />
<input name="checkbox" value="4" type="checkbox" />
<button id="button" type="button">button</button>

Jquery :

$(document).ready(function () {

  var tmp = [];

  $("input").each(function() {
    if ($(this).is(':checked')) {
      var checked = ($(this).val());
      tmp.push(checked);
    }
  });

  $('#button').on('click', function () {
        alert(tmp);
  });

});

What am I doing wrong ?

2
  • Are you deliberately not allowing values to be removed from the array, or is that your next step? Commented May 14, 2017 at 9:22
  • @DavidThomas If the user removes a value I'll update it onto the array when submiting Commented May 14, 2017 at 9:25

7 Answers 7

5

You are not invoking checkbox change event. Use this:

$("input[name='checkbox']").change(function() {
  var checked = $(this).val();
  if ($(this).is(':checked')) {
    tmp.push(checked);
  } else {
    tmp.splice($.inArray(checked, tmp),1);
  }
});

http://jsfiddle.net/fx7su2rp/694/

Sign up to request clarification or add additional context in comments.

2 Comments

@Lindow, For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse. For more info. click on link which is shared.
I see, I just saw a little problem, probably because I didn't mention it but how can I update my checkboxes when the user uncheck a value ?
3

You are verifying if they are checked at the beginning (when none is checked) so this is why you get that empty array.

You should be handling clicks on the inputs in order to update the array. Check this out.

$(document).ready(function () {

  var tmp = [];

  $("input").click(function() {
    if ($(this).is(':checked')) {
      var checked = ($(this).val());
      tmp.push(checked);
    } else {
      tmp.splice($.inArray(checked, tmp),1);
    }
  });

  $('#button').on('click', function () {
        alert(tmp);
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="checkbox" value="1" type="checkbox" />
<input name="checkbox" value="2" type="checkbox" />
<input name="checkbox" value="3" type="checkbox" />
<input name="checkbox" value="4" type="checkbox" />
<button id="button" type="button">button</button>

Notice the $('input').click() there.

1 Comment

What if the user clicks a checkbox 2 or more times?
1

You need to handle checked event of each checkbox.

So that you can push it into array For more detail, you can see here

$(document).ready(function () {

  var tmp = [];
  
  $("input").each(function() {
    $(this).change(function() {
    if(this.checked) {
      tmp.push(this.checked);
    }
});})
 
  $('#button').on('click', function () {
		alert(tmp);
    console.log(tmp);
  });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="checkbox" value="1" type="checkbox" />
<input name="checkbox" value="2" type="checkbox" />
<input name="checkbox" value="3" type="checkbox" />
<input name="checkbox" value="4" type="checkbox" />
<button id="button" type="button">button</button>

Comments

1

Either you can do on change as the other sais, but it's more effective to only run the code when the user presses the button, so make a function and call that function when the user presses the button:

http://jsfiddle.net/fx7su2rp/693/

$(document).ready(function () {


  $('#button').on('click', function () {
        alert(check_boxes());
  });

});

function check_boxes() {
var tmp = [];
  $("input").each(function() {
    if ($(this).is(':checked')) {
      var checked = ($(this).val());
      tmp.push(checked);
    }
  });
  return tmp;
}

Comments

1

Add a click function on your checkbox and each click, if checked, then push the value in tmp variable.

  $('#button').on('click', function () {
  var tmp = [];
      $("input").each(function() {
          if ($(this).is(':checked')) {
          var checked = ($(this).val());
          tmp.push(checked);
        }
      });
  alert(tmp);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="checkbox" value="1" type="checkbox" />
<input name="checkbox" value="2" type="checkbox" />
<input name="checkbox" value="3" type="checkbox" />
<input name="checkbox" value="4" type="checkbox" />
<button id="button" type="button">button</button>

Comments

1

As other answers already suggested, you have to update your values array anytime a change event occurs on any checkbox you wish to monitor.

Other answers work just fine, but I thought I'd post a more plain javascript answer. I think this is a bit cleaner and more expressive than a jQuery .each() loop, and saves us from querying values in, pushing into, and splicing from an intermediate array manually.

Let's create a regular array containing your checkboxes called checkboxesArray in addition to the jQuery collection, and filter then map that array in our change handler:

$(document).ready(function () {

  let $checkboxes = $('[name="checkbox"]');
  let checkboxesArray = [].slice.call($checkboxes);
  let $output = $('#output');
  let values = [];
  
  $checkboxes.on('change', () => {
    values = checkboxesArray
      .filter((checkbox) => checkbox.checked)
      .map((checkbox) => checkbox.value);
      
    // Preview:
    $output.append('<div>' + values.join(', ') + '</div>');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="checkbox" value="1" type="checkbox" />
<input name="checkbox" value="2" type="checkbox" />
<input name="checkbox" value="3" type="checkbox" />
<input name="checkbox" value="4" type="checkbox" />
<button id="button" type="button">button</button>

<div id="output"></div>

Comments

0

This will help you :

$("#button").click(function (e) { 
     var tmp = [];              
     $('.tmp').each(function(){
     if ($(this).is(':checked')) {
     var checked = ($(this).val());
     tmp.push(checked);
   }
 });
 console.log(tmp);
}

Comments

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.