Reputation: 3205
I am trying to find a way to reuse a function that is fired from an event binding.
This issue is caused from browsers remembering checkbox states, so I have to fire the function on document ready.
I know I could put setGrid()
in an anonymous function and pass in the element instead, but that would make it difficult to unbind the specific event.
HTML:
<input type="checkbox" value="grid" id="checkbox-grid">
Javascript:
function setGrid(e) {
var $this = $(e.target); // "error: e is undefined" on situation 2
if( $this.is(':checked') ){
// do something if checkbox is checked
}
else{
// do something if checkbox isn't
}
}
// 1. event binding
$('#checkbox-grid').on('change', setGrid);
// 2. function fired on page ready
setGrid();
Upvotes: 0
Views: 136
Reputation: 5712
You can use the first solution you have. Since you're using jQuery, it's dead easy to fire the function, you just fire the event it's associated with. So:
$('#checkbox-grid').on('change', setGrid); // to set it up; then
$('#checkbox-grid').trigger("change"); // fires the change event of the
// checkbox, so fires the function.
You can do it with any event, just substitute change
for the event. However, since you're probably doing it with change
for a reason, it may be best to leave it like that.
Hope this helps.
Upvotes: 2