You are viewing limited content. For full access, please sign in.

Question

Question

Help with JavaScript to auto check 'check-boxes' based on selection

asked on October 3, 2016 Show version history

Hi there, 

I've got a client that is trying to build a form and needs some help with JavaScript. I've tried to get this to work for them but I must be missing something. I've read the other Answers and although they are close, it's not exact and therefore is not working. 

 

They have a form with a checkbox item called Field5, with 3 options. So those are Field5-0, Field5-1 and Field5-2. 

 

Then they have over 10 additional check box items, each with 3 options as well. Basically all they want to do is if Field5-0 is checked, check all check box items in Fieldx-0. They don't mind typing it all out (So like Field6-0, Field7-0, Field8-0, and so on). 

If Field5-1 is checked, check all the Fieldx-1 (Field6-1, Field7-1, etc)

If Field5-2 is checked, check all the Fieldx-2 (Field6-2, Field7-2, etc)

This seems very straight forward but any code I try for them is not working the way they need it. 

 

Thanks in advance!!

0 0

Answer

SELECTED ANSWER
replied on October 3, 2016

First, I'd like to ask... would it be better to redesign the form if you have 10+ sets of checkboxes, and they all get set to the same values? I don't know what you're trying to do, but usually simpler is better!

If you do decide that it's best to keep on the path you described above, I'd recommend adding some classes to your fields rather than using a bunch of hard-coded Field IDs. Add a CSS class CheckboxController to the field that you are using to set all the other ones (Field5). Then add a different class, like DependentCheckbox, to all your other checkboxes. Using those classnames, the Javascript below should do what you want.

$(document).ready(function(){
  $('.CheckboxController input').click(function(){
    var i = $(this).closest('span').index();
    var val = $(this).is(':checked');
    $('.DependentCheckbox span:nth-child('+(i+1).toString()+') input').prop('checked',val);
  });
});

 

3 0
replied on October 3, 2016

I knew it had to be fairly simple, they said that worked. Thanks Scott, I appreciate the quick help!

0 0

Replies

You are not allowed to reply in this post.
You are not allowed to follow up in this post.

Sign in to reply to this post.