user1885099
user1885099

Reputation: 150

jquery checkbox checked

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!

Upvotes: 3

Views: 351

Answers (5)

adeneo
adeneo

Reputation: 318332

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

Upvotes: 1

Sridhar Narasimhan
Sridhar Narasimhan

Reputation: 2653

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

Upvotes: 0

Murali Murugesan
Murali Murugesan

Reputation: 22619

Try the below

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

Upvotes: 0

Viktor S.
Viktor S.

Reputation: 12815

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"))

Upvotes: 0

BuddhiP
BuddhiP

Reputation: 6461

Try this:

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

Upvotes: 1

Related Questions