2
\$\begingroup\$

I have two different set of checkboxes. With the coffescript code below I set the maximum amount of checkable items at 3. I would like to refactor this code, to be cleaner and compact, but I can't get it.

$("div.feature_list :checkbox").click ->
 if $("div.feature_list :checked").length >= 3
 $("div.feature_list :checkbox:not(:checked)").attr "disabled", "disabled"
 $("div.feature_list :checkbox:not(:checked)").button disabled: true
 else
 $("div.feature_list :checkbox:not(:checked)").button disabled: false
$("div.style_list :checkbox").click ->
 if $("div.style_list :checked").length >= 3
 $("div.style_list :checkbox:not(:checked)").attr "disabled", "disabled"
 $("div.style_list :checkbox:not(:checked)").button disabled: true
 else
 $("div.style_list :checkbox:not(:checked)").button disabled: false 
Quill
12k5 gold badges41 silver badges93 bronze badges
asked Oct 6, 2012 at 19:16
\$\endgroup\$
1
  • 1
    \$\begingroup\$ FYI, to enable/disable a button use .prop('disabled', true_or_false) instead of setting the attribute. \$\endgroup\$ Commented Oct 6, 2012 at 19:17

1 Answer 1

5
\$\begingroup\$

Step 1: DRY. Encapsulate the "limit checkboxes" behavior in a function

limitCheckboxesIn = (container, limit = 3) ->
 checkboxes = $(container).find ":checkbox"
 checkboxes.on "click", (event) ->
 checked = checkboxes.filter ":checked"
 unchecked = checkboxes.not checked
 state = disabled: checked.length >= limit
 unchecked.prop(state).button state

Step 2: ... well, that pretty much it. Call it like so:

$ ->
 limitCheckboxesIn "div.feature_list"
 limitCheckboxesIn "div.style_list"

Here's a demo

By the way, if you just want the most compact solution, you can skip some assignments:

limitCheckboxesIn = (container, limit = 3) ->
 checkboxes = $(container).find ":checkbox"
 checkboxes.on "click", (event) ->
 disabled = checkboxes.filter(":checked").length >= limit
 checkboxes.not(":checked").prop({disabled}).button {disabled}

Personally, I find this a little less readable, but it's a matter of taste; the code's functionally identical.

answered Oct 6, 2012 at 20:27
\$\endgroup\$
2
  • \$\begingroup\$ It works with plain checkboxes but it doesnt work with jquery ui buttonset. I think the last line should be different \$\endgroup\$ Commented Oct 7, 2012 at 0:29
  • \$\begingroup\$ @framomo86 Whoops, you're right - I've corrected my answer, and the demo. \$\endgroup\$ Commented Oct 7, 2012 at 10:33

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.