简体   繁体   English

如果选中复选框,则传递复选框值

[英]Pass checkbox value IF the checkbox is checked

I have a list of checkboxes that looks like this: 我有一个复选框列表,看起来像这样:

<div class="checkbox">
<label><input type="checkbox" value="west" name="west" id="west" checked="{{isChecked}}">West</label>
</div>
<div class="checkbox">
<label><input type="checkbox"  checked="{{isChecked}}" name="airport" id="airport" value="airport">Airport</label>
</div>
<div class="checkbox">
<label><input type="checkbox"  checked="{{isChecked}}" name="north" id="north" value="north">North</label>
</div>

I have managed to pass the status of each checkbox as a boolean to the collection like this: 我设法将每个复选框的状态作为布尔值传递给集合,如下所示:

var eventLocation = [
event.target.west.checked,
event.target.airport.checked,
]

However, I would like to pass only the value of the checked checkboxes. 但是,我只想传递选中的复选框的值。 I know I can pass the value of the checkboxes with event.target.west.value , but to get only the checked ones I would have to write many conditionals, which would not scale well. 我知道我可以通过event.target.west.value传递复选框的值,但是要仅获取已选中的复选框,我将不得不编写许多条件,但条件伸缩性不佳。 Is there a better way of doing this? 有更好的方法吗?

Thank you! 谢谢!

You can quickly gather all checked checkboxes with: 您可以使用以下方法快速收集所有选中的复选框:

var checked = $("input:checked");

This will return an array that you can loop over to get the id, value, or name. 这将返回一个数组,您可以循环获取id,值或名称。

checked.forEach(function(c){
  console.log('input id: '+c.id+' name: '+c.name+' value: '+c.val+' is checked!');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM