How to use Meteor and jquery events?

I have a check all / uncheck all checkbox in the header of a table. Based on the advice of others, I changed from using jQuery and document ready to using meteor events. The problem is, it no longer does the actual check/uncheck all. My HTML is:

Check/Uncheck all checkbox:

<input type="checkbox" id="theSitesSelectAll">

The checkbox in the table:

<input type="checkbox" class="theSiteCheckbox" id="{{ _id }}">

My meteor js code is:

Template.body.events({
  'click #theSitesSelectAll': function() {
    $(".theSiteCheckbox").prop('checked', $(this).prop("checked"));
    console.log("The select / deselect all checkbox is set to: " + $(this).prop("checked"));
  }
});

What I get in my console is: The select / deselect all checkbox is set to: undefined

How can I make this work again?

Something like this will work:

'click #theSitesSelectAll': function (event, instance) {
  const $checkbox = instance.$('.theSiteCheckbox');
  $checkbox.prop('checked', !$checkbox.prop('checked'));
}

Thank you! That definitely works. Not sure why exactly my code didn’t, but I’ll go with what you gave me.

Check out ViewModel, you might like it. Your problem is reduced to the following:

<body>
  <input type="checkbox" {{b "check: allChecked, change: siteCheckboxes.prop('checked', allChecked)"}}>Check All <br>
  <input type="checkbox" {{b "refGroup: siteCheckboxes"}}> Check 1 <br>
  <input type="checkbox" {{b "refGroup: siteCheckboxes"}}> Check 2 <br>
  <input type="checkbox" {{b "refGroup: siteCheckboxes"}}> Check 3 <br>
</body>

No ids, classes, selectors, $, or event maps.

You can do the check/uncheck in code too:

<body>
  <input type="checkbox" {{b "check: allChecked, change: toggleCheckboxes"}}>Check All<br>
  <input type="checkbox" {{b "refGroup: siteCheckboxes"}}> Check 1 <br>
  <input type="checkbox" {{b "refGroup: siteCheckboxes"}}> Check 2 <br>
  <input type="checkbox" {{b "refGroup: siteCheckboxes"}}> Check 3 <br>
</body>
Template.body.viewmodel({
  allChecked: false,
  toggleCheckboxes: function() {
    this.siteCheckboxes.prop('checked', this.allChecked())
  }
});
1 Like