【问题标题】:How to get all the value of checked checkboxes using jquery/javascript? [duplicate]如何使用 jquery/javascript 获取选中复选框的所有值? [复制]
【发布时间】:2019-06-19 02:44:10
【问题描述】:

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

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>

【问题讨论】:

  • 您可以使用map() 来构建您的检查值数组。有关详细信息,请参阅副本

标签: javascript jquery html


【解决方案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>

【讨论】:

  • @ashwinkarki,不客气:)
  • 如何在页面加载时取消选中复选框 OTHERS ?有什么办法吗?
  • 非常感谢你让我度过了愉快的一天
  • @ashwinkarki,不客气:)
  • 今天过得愉快,非常感谢@mamun
猜你喜欢
  • 2013-01-06
  • 2015-02-19
  • 2019-01-05
  • 1970-01-01
  • 2013-01-11
  • 1970-01-01
  • 1970-01-01
  • 2014-09-11
  • 2015-02-23
相关资源
最近更新 更多