mercredi 18 mars 2015

How to prevent multiple code execution on checkbox click in jQuery?

On my page I have a checkboxes like this:



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


Each time user check or uncheck it I want to execute some jQuery code. Here's sample of this code:



$("input[type=checkbox]").click(function () {
if ($(this).is(':checked')) {
// Calculate something here
}
else {
// Or calculate something here
}
});


Here's the problem: if user will click on checkbox multiple time really quick, some of the code will be executed multiple times, because it will trigger click function every time, but browser will not change 'check' status that quick!


How to prevent this?


I thought to put something like:



$("input[type=checkbox]").click(function () {
if ($(this).is(':checked')) {
// Disable checkbox
$(this).disabled = true;

// Calculate something here

// Enable it back
$(this).disabled = false;
}
else {
// Or calculate something here
}
});


How can I make my code to execute exact in this sequence? Disable > then execute code > then enable back?


Thanks





Aucun commentaire:

Enregistrer un commentaire