2
\$\begingroup\$

I have the following jQuery click functions:

$childCheckbox.click(function(){
    if(!$(this).hasClass('checked') && !$parentCheckbox.hasClass('checked')){
        $(this).attr('checked', 'checked').addClass('checked');
        $parentCheckbox.prop('indeterminate',true);     
    }
    else if($(this).hasClass('checked')){
        $(this).removeAttr('checked', 'checked').removeClass('checked');
        $parentCheckbox.prop('indeterminate',false);
    }
});

$subparentCheckbox.click(function(){
    if(!$(this).hasClass('checked') && !$parentCheckbox.hasClass('checked')){
        $(this).attr('checked', 'checked').addClass('checked');
        $parentCheckbox.prop('indeterminate',true);     
    }
    else if($(this).hasClass('checked')){
        $(this).removeAttr('checked', 'checked').removeClass('checked');
        $parentCheckbox.prop('indeterminate',false);
    }
});

As you can see both are exactly the same with the exception of the "selector". Is there a good way to combine these to minimize code?

\$\endgroup\$
  • \$\begingroup\$ Tip: Store the result of $(this) in a temporary variable to avoid repeated calls to jQuery: var $this = $(this); \$\endgroup\$ – David Harkness Apr 16 '13 at 23:27
5
\$\begingroup\$

Here are 3 - there are more, no doubt

  1. Give both checkboxes a class and use that as the selector

    $(".someClass").click( ... )
    
  2. Declare the event handler elsewhere, and use it anywhere:

    function checkboxClick(event) {...};  
    
    $subparentCheckbox.click(checkboxClick);  
    $childCheckbox.click(checkboxClick);
    
  3. Use .add to combine the two checkboxes into one collection before calling .click like so

    $subparentCheckbox.add($childCheckbox).click(...)`
    
\$\endgroup\$
  • \$\begingroup\$ You can call the .on() method straight away, since if you look in jQuery source, .click() refers right back to .on() anyways. \$\endgroup\$ – Jonny Sooter Feb 22 '13 at 17:04
  • 1
    \$\begingroup\$ @JonnySooter True. I actually prefer using .on() in my own code even when there are aliasses like .click(). Keeps the code consistent. \$\endgroup\$ – Flambino Feb 22 '13 at 17:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.