当我的页面打开时,默认情况下会选中所有复选框,并且在提交表单时,我无法获取数组中选中复选框的值。用户可能不会单击复选框,因为默认情况下它是全部选中的。所以我尝试使用以下方法接收检查值:
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>
您可以简单地使用 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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句