0

When my page opens then all the checkboxes are checked by default and while submitting the form, I am not able to get the value of the checked checkboxes in a array. The user may not click the checkboxes as it is by default all checked. So I tried to receive the checked value using:

var valores = (function() {
    var valor = [];
    $('input.className[type=checkbox]').each(function() {
        if (this.checked)
            valor.push($(this).val());
    });
    return valor;

})();

console.log(valores);

My codes for the checkboxes is:

<div class="form-group" id="documents">
   <label> <input id="check_id3" type="checkbox" value="3" class="chk3" checked=""> <span>OTHERS</span>
   <br>
   </label>
   <div style="padding-bottom:5px"></div>
   <label> <input id="check_id1" type="checkbox" value="1" class="chk1" checked=""> <span>Invoice</span>
   <br>
   </label>
   <div style="padding-bottom:5px"></div>
   <label> <input id="check_id2" type="checkbox" value="2" class="chk2" checked=""> <span>Packing List</span>
   <br>
   </label>
   <div style="padding-bottom:5px"></div>
</div>
Mamun
  • 66,969
  • 9
  • 47
  • 59
ashwin karki
  • 643
  • 5
  • 19
  • 35

1 Answers1

1

You can simply use jQuery's .map() and .get() on all the checked check boxes:

$("label > span:contains('OTHERS')").prev().prop('checked', false);

var valor = $('input[type=checkbox]:checked').map(function(){
  return this.value;
 }).get();
console.log(valor);

$("label > span:contains('OTHERS')").prev().change(function(){
  if(!this.checked) alert('Others unchecked');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group" id="documents">
   <label> <input id="check_id3" type="checkbox" value="3" class="chk3" checked=""> <span>OTHERS</span>
   <br>
   </label>
   <div style="padding-bottom:5px"></div>
   <label> <input id="check_id1" type="checkbox" value="1" class="chk1" checked=""> <span>Invoice</span>
   <br>
   </label>
   <div style="padding-bottom:5px"></div>
   <label> <input id="check_id2" type="checkbox" value="2" class="chk2" checked=""> <span>Packing List</span>
   <br>
   </label>
   <div style="padding-bottom:5px"></div>
</div>
Mamun
  • 66,969
  • 9
  • 47
  • 59