Search code examples
meteormeteor-blaze

Get each checked checkbox value


I'm trying to get the value of each checked box that has been selected as true. Each time I select a checkbox it grabs the value of that checkbox instead of all the selected checkboxes.

Path: talentList.html

<fieldset>        
  <div class="checkbox">
    <label>
      <input name="specialisation" type="checkbox" value="Accounting Firm"> Accounting Firm
    </label>
  </div>

  <div class="checkbox">
    <label>
      <input name="specialisation" type="checkbox" value="Accounting in Industry"> Accounting in Industry
    </label>
  </div>
</fieldset>

Path: talentList.js

Template.talentList.events({
    'change [name="specialisation"]': function ( event, template ) {
        let specialisation = event.target.value;
        template.candidateListFilter.set( specialisation );
    }
});

Solution

  • There is only one target set in the event handler so event.target.value will be a scalar instead of an array. You need to iterate over the array of checkboxes.

    Template.talentList.events({
      'change [name="specialisation"]': function ( event, template ) {
        $.each($('[name="specialisation"]'),function(i,cb){
          let specialisation = cb.value;
          template.candidateListFilter.set( specialisation );
        });
      }
    });
    

    To be honest this seems like an odd pattern. If you want to update a document whenever a checkbox is checked/unchecked you shouldn't have to set the state of all the other checkboxes at the same time, you should be able to just poke the one you want.