3

I have this:

<div id="container1">
   <div class="block1">
      <input class="pos2" type="checkbox" /><label>Category1</label><br>
      <input class="pos3" type="checkbox" /><label>Subcategory1</label><br>
      <input class="pos3" type="checkbox" /><label>Subcategory1</label>
   </div>

   <div class="block1">
      <input class="pos2" type="checkbox" /><label>Category2</label><br>
      <input class="pos3" type="checkbox" /><label>Subcategory2</label>
      <input class="pos3" type="checkbox" /><label>Subcategory2</label>
   </div>
</container>

I am trying to use jquery to auto-check the checkboxes. For example: if I would check 'pos2' it would auto-check pos3.

I used this:

$("#container1 .block1 .pos2").click(function(){
     $(".block1").children(".pos3").attr('checked', 'checked');
});

But I need it to only check 'pos3' from the div I clicked on.

Note: The checkboxes are generated with PHP from entrys in a database. Their numbers can vary, thus I can't use ids on elements.

Can anyone help me on this?

Thanks in advance!

5 Answers 5

1

Try this:

$(".pos2").click(function(){
   $(this).siblings(".pos3").attr('checked', 'checked');
});
Sign up to request clarification or add additional context in comments.

Comments

1
$("#container1 .block1 .pos2").on('change', function(){
    $(this).siblings('.pos3').prop('checked', this.checked);
});

Comments

0

This code should work:

$("#container1 .block1 .pos2").click(function(){
    $(this).parent().find('.pos3').attr('checked', 'checked');
});

in handler function this points to clicked object. .parent will get parent of that checkbox and find will search for .pos3 inside parent div only (like $(".block1 .pos3"))

1 Comment

@user1885099 Instead of "thank you" commenting, JFYI: meta.stackexchange.com/questions/5234/…. And besides, BuddhiP's answer with .siblings is better - it is shorter and do the same thing. Plus it should be faster.
0

Try the below

 $("#container1 .block1 .pos2").click(function(){
    $(this).parents("div.block1:first")
     .children(".pos3").attr('checked', 'checked');
 });

Comments

0
$("#container1 .block1 .pos2").click(function(){
$(this).siblings(".pos3").attr('checked', 'checked');
});

Comments

Your Answer

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.