user1650108
user1650108

Reputation: 75

Can't get checkboxes to check and uncheck others

I need help trying to get some of the checkboxes to check others when they themselves are checked.

i.e. In the JSFiddle link (http://jsfiddle.net/sHKRM/) when the first option 'Milk and Bread' is checked, I need the checkboxes for 'Bread' and 'Milk' to be checked as well as the 'Milk and Bread' box to remain checked.

This needs to be done multiple times on the page (e.g. Chicken and Vegetables should check both of those).

I also need to be able to reverse the selection if the user unchecks. i.e. If 'Milk and Bread' is ticked, and the two are ticked as a result, they must both become unticked if the 'Milk and Bread' checkbox is unchecked.

I have found various solutions on stackoverflow if the checkboxes were a list, but I cannot get it to work with the rest of the script (once the appropriate items are checked, the user generates the list and then copies it to the clipboard).

As you can see in the fiddle, there needs to be multiple 'combinations' in that a user might want tick 'Milk and Bread' and 'Chicken and Vegetables' so my question is how can this be achieved using the structure I have at the moment (i.e. everything in a table as shown below and not just as a list)?

    <tr>
    <td><input type='checkbox' name='pe_gen1' value='- Milk and Bread' />&nbsp;Milk and Bread</td>
    <td><input type='checkbox' name='pe_gen2' value='- Bread' />&nbsp;Bread</td>
    </tr>
    <tr>
    <td><input type='checkbox' name='pe_gen2' value='- Milk' />&nbsp;Milk</td>
    <td><input type='checkbox' name='pe_gen2' value='- Cookies' />&nbsp;Cookies</td>
    </tr>

Upvotes: 1

Views: 161

Answers (1)

Matt Ball
Matt Ball

Reputation: 359786

Shameless self-promotion: this looks like a good use-case for the jQuery-CheckAll plugin I've written. You could apply it in this case like so:

$('input[value="- Milk and Bread"]')
    .checkAll('input[value="- Milk"], input[value="- Bread"]');

http://jsfiddle.net/mattball/cL8LL/

Upvotes: 2

Related Questions