简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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