Reputation: 13
I have a group of checkboxes in a div and I use a check all/uncheck all function.
HTML:
<div id="available_options" class="input">
<ul class="inputs-list">
<li>
<label>
<input type="checkbox" name="options" id="option_1" />
<span>Option1</span>
</label>
</li>
<li>
<label>
<input type="checkbox" name="options" id="option_2" />
<span>Option2</span>
</label>
</li>
</ul>
</div>
<a id="check_all_options">Check all</a> / <a id="uncheck_all_options">Uncheck all</a>
Jquery:
$('#check_all_options').click(function(e){
$('#available_options input').attr('checked', 'checked').change();
});
$('#uncheck_all_options').click(function(e){
$('#available_options input').removeAttr('checked').change();
});
$('#available_options input').live('change', function(e){
alert('test');
});
At the moment my alert is fired whenever a checkbox is checked/unchecked which is good. However when using the "check all"/"uncheck all" the alert is fired multiple times (each checkbox is firing an event). I have tried with stopPropagation but I can't get it to do what I want.
Any ideas how on can I get it to fire a single event every time a modification is made? I want to be able to get the options that are selected in order to launch a database query. But I do not want to launch the query multiple times when the checkall/uncheckall is used.
Thanks
Upvotes: 1
Views: 216
Reputation: 13166
You can see an example in this page: http://briancray.com/2009/08/06/check-all-jquery-javascript/
Upvotes: 0
Reputation: 10221
Reposting comment as answer:
Why do you explicitly trigger change event? Simply calling your ajax/db query function from all 3 handlers would do it. See jsfiddle for example.
Upvotes: 0
Reputation: 359966
Shameless self-promotion: you might want to use this jQuery plugin I wrote for this exact task. It would look something like this:
$('#check_all_options').checkAll('#available_options input[type="checkbox"]', {
reportTo: function (numChecked) {
console.log(numChecked);
}
});
If you need more information in the reportTo
callback beyond the number of boxes checked, I strongly encourage you to submit an issue, and I can work on improving this little project!
If you don't want to use my plugin, that's cool too. You're still welcome to look at how it works, to understand how it fires only a single event for changes.
Upvotes: 2