Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 924
user1885099 Avatar asked Jul 16 '26 04:07

user1885099


2 Answers

Try this:

$(".pos2").click(function(){
   $(this).siblings(".pos3").attr('checked', 'checked');
});
like image 146
BuddhiP Avatar answered Jul 18 '26 18:07

BuddhiP


$("#container1 .block1 .pos2").on('change', function(){
    $(this).siblings('.pos3').prop('checked', this.checked);
});
like image 24
adeneo Avatar answered Jul 18 '26 19:07

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!