11

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?

4 Answers 4

24

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
});
Sign up to request clarification or add additional context in comments.

3 Comments

ugh.. the difference a space makes mahalos
@Jared - input[type=checkbox] is a valid CSS selector. When possible, jQuery will pass the selector along to querySelectorAll, which is far more efficient than jQuery's own implementation of :checkbox.
and how to get text of selected checkbox ?
1

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();
}
});

Comments

1

I had a similar issue, and this StackOverflow page is the first answer I stumbled upon, but wasn't really satisfied with it. I found this article https://www.kevinleary.net/jquery-checkbox-checked/ with a better solution.

$('input[name="subscribe"]').on('click', function(){
    if ( $(this).is(':checked') ) {
        $('input[name="email"]').show();
    } 
    else {
        $('input[name="email"]').hide();
    }
});

Comments

0

Use this:

$('#part1 input:checkbox').click(...)

http://api.jquery.com/checkbox-selector/

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.