Scott Flack
Scott Flack

Reputation: 619

jQuery UI Button on checkbox will not work if quickly clicked multiple times

I have a page setup with some checkboxes, that UI.button applied to them. They each have a onclick event, that calls a function that will display a tab (if checked) or remove a tab (if unchecked).

The problem is, if you click them quickly, you can end up with a tab displaying, and the checkbox showing as unchecked, or vice-versa.

I've tried removing the onclick event, making it a dblclick event as well, and also disabling the checkbox via attr() and .button('option', 'disabled', true) with no luck in it solving the issue.

My relevant code is below:

PHP that creates the checkboxes:

$output .= '<input onclick="toggleTab(\'' . $group['_id'] . '\', this);" type="checkbox" name="groups" value="'.$group['_id'].'" id="groups_'.$group['_id'].'" /><label id="l_'.$group['_id'].'" for="groups_'.$group['_id'].'">'.$group['name'].'</label>';

javascript function called on click:

function toggleTab (id, elem) {
if ($(elem).is(':checked')) {
    $('#tab_' + id ).show();
} else {
    var currentTab = $('#tabPricing .ui-tabs-panel:not(.ui-tabs-hide)');
    tab = currentTab.prop("id");
    if (tab == 'tab' + id) {
    $('#tabPricing .innerTabs').tabs('select', 'tabDefault');
    }
    $('#tab_' + id ).hide();
}

}

I know it's likely a JavaScript problem in general, I just can't seem to find a good way around it.

Upvotes: 1

Views: 619

Answers (1)

SpYk3HH
SpYk3HH

Reputation: 22580

I've had this problem before and it appears to be timing. using is:checked on click command in some browsers (as my problem was) doesnt time right. What I mean to say, the problem I found was that too often the click was executing faster than the lib makeing the checkbox checked. What I did to counter was to NOT USE onclick or .click, but .change instead

for example

$("input[type=checkbox]").change(function(e) {
    // preform some actions here, like show or hiding somthing or whatever
});

from my experience, .change fires everytime as checkbox is checked or unchecked, thus you get a much more acurate reading

Fiddle Example

Upvotes: 1

Related Questions