如何使用jquery / javascript获取所有选中复选框的值?

时间:2019-01-25 09:27:20

标签: javascript jquery html

当我的页面打开时,默认情况下会选中所有复选框,并且在提交表单时,我无法获取数组中选中的复选框的值。用户可能不会单击复选框,因为默认情况下所有复选框均已选中。所以我尝试使用以下方法接收检查的值:

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

})();

console.log(valores);

我的复选框代码为:

<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>

1 个答案:

答案 0 :(得分:1)

您只需在所有已选中 复选框上使用jQuery的.map().get()

$("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>

相关问题