Javascript : Pushing a value of checkbox if checked and the value of not checked together

So I have multiple checkboxes.

<input type="checkbox" value="special" name="special_round[]">special1
<input type="checkbox" value="special" name="special_round[]">special2
<input type="checkbox" value="special" name="special_round[]">special3
<input type="checkbox" value="special" name="special_round[]">special4

I can only do is to push value that has checked the input

$('#click').on('click', function(e){
    e.preventDefault();
    e.stopPropagation();
var specialSequences = [];
   $('input[name="special_round[]"]:checked').each(function(i, v) {
   specialSequences.push($(v).val());
});
   alert(specialSequences);

});

The output if i check the special1 and special4 is

special,special

How do i make it like this,

special, 0 , 0, special //or
special, " ", " ", special

//or if i checked the special2 and speial4 the output should 
" ", special , " " , special

https://jsfiddle.net/t6fL04cm/

Upvotes: 0

Views: 519

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

You need to iterate through all checkboxes and check which one is "checked" and which - is not.
Use the following approach:

...
  var specialSequences = [];
  $('input[name="special_round[]"]').each(function(i, v) {
    var current = ($(v).is(":checked"))? $(v).val() : "";
    specialSequences.push(current);
  });

https://jsfiddle.net/t6fL04cm/1/

About jQuery .is() method: https://api.jquery.com/is/

Upvotes: 3

Related Questions