Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check all checkboxes in current form with jquery?

Consider this simple example code:

<form name="text" id="frm1" method="post">
  <input type="checkbox" name="name[]" value="1000"> Chk1<br>
  <input type="checkbox" name="name[]" value="1001"> Chk2<br>
  <input type="checkbox" name="name[]" value="1002"> Chk3<br>
  <input type="checkbox" name="name[]" value="1003"> Chk4<br>
  <input type="checkbox" id="select_all"/> Select All<br>  
</form>

<form name="text" id="frm2" method="post">
  <input type="checkbox" name="name[]" value="4000"> Chk1<br>
  <input type="checkbox" name="name[]" value="4001"> Chk2<br>
  <input type="checkbox" name="name[]" value="4002"> Chk3<br>
  <input type="checkbox" name="name[]" value="4003"> Chk4<br>
  <input type="checkbox" id="select_all"/> Select All<br>  

I'm trying to get Select All to work in each form (forms are dynamically generated in my production code and have different, varying names)

I'm using this jquery but select_all only works for only the first form; it has not affect on forms below the first.

$('#select_all').change(function() {
  var checkboxes = $(this).closest('form').find(':checkbox');
  if($(this).is(':checked')) {
      checkboxes.attr('checked', 'checked');
  } else {
      checkboxes.removeAttr('checked');
  }
});

I can't figure out how to Check All checkboxes in any :checkbox contained within the form ID.

Can someone point me in the right direction?

Many thanks

like image 442
Chris Avatar asked Nov 13 '10 21:11

Chris


2 Answers

You have multiple elements with the same ID, which is invalid HTML and is causing the problem you're seeing. Change id="select_all" to class="select_all", and $('#select_all') to $('.select_all'), and you should be good.

like image 133
Domenic Avatar answered Sep 22 '22 22:09

Domenic


You have two elements with id select_all; that's not allowed. Change that to a class and try this:

$('.select_all').change(function() {
  var checkboxes = $(this).closest('form').find(':checkbox');
  checkboxes.attr('checked', $(this).is(':checked'));
});
like image 39
kevingessner Avatar answered Sep 21 '22 22:09

kevingessner