Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery bind click event to checkboxes

Tags:

jquery

bind

Here's a basic view of what my html looks like:

<form>
  <div id="part1">
     // some html form elements including checkboxes
  </div>
  <div id="part2">
    // more html code with more checkboxes
  </div>
  <div id=part2">
     // data table with numerous checkboxes built dynamically
  </div
</form>

What I need to do is bind the .click() event to the checkboxes in part 1, 2, and 3 seperately. I've tried this $('#part1:checkbox').click(...) but that didn't work. If I use $("form :checkbox").click(...) same click event is bound to all checkboxes and not just one set. How would I seperate these?

like image 923
iJared Avatar asked Jun 27 '12 23:06

iJared


2 Answers

You're almost there. You just need a space to separate the descendant selector:

$('#part1 :checkbox').click(function(){
    // code goes here
});

To increase performance, you might wanna use this:

$('#part1 input[type=checkbox]').click(function(){
    // code goes here
});
like image 161
Joseph Silber Avatar answered Nov 02 '22 04:11

Joseph Silber


Or you give same class name for all checkboxes and give the corresponding div ID for the checkbox also, so you can use the following code,

<input type="checkbox" class="checkall" id="part1">Part 1 

and your script goes like this.

$('.checkall').click(function () {
if (this.checked == false) {
$("." + $(this).attr("id")).hide();
}
});
like image 34
user3512003 Avatar answered Nov 02 '22 03:11

user3512003