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\$
1
  • \$\begingroup\$ Tip: Store the result of $(this) in a temporary variable to avoid repeated calls to jQuery: var $this = $(this); \$\endgroup\$ Commented Apr 16, 2013 at 23:27

1 Answer 1

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\$
2
  • \$\begingroup\$ You can call the .on() method straight away, since if you look in jQuery source, .click() refers right back to .on() anyways. \$\endgroup\$ Commented Feb 22, 2013 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\$ Commented Feb 22, 2013 at 17:53

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.