Search code examples
javascriptarraysmeteorcheckboxmeteor-helper

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!


Solution

  • 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!');
    });