Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling jQuery function from different elements

I'm pretty new to the jQuery world, so I'm hoping for some help.

I am creating a page that has a div that has a number of checkboxes inside of it.

Each of these checkboxes are contained in their own divs as well.

<div>
    <div>  
        <input type='checkbox' name='cb1' />
        <div id="info1">
            Hide
        </div>  
    </div>  
    <div>  
        <input type='checkbox' name='cb2' />
        <div id="info2">
            Hide
        </div>  
    </div>  
</div> ​

I need to write a jQuery function that be able to capture whenever either checkbox (cb1 or cb2) is clicked to hide/show it's corresponding 'info' div, (info1 or info2).

I'm going to have 100+ checkboxes so I'm hoping there is a way to do this without having to write 100+ functions for click().

Thanks,
Mark

like image 571
Mark Avatar asked Jun 22 '26 13:06

Mark


2 Answers

It's a lot easier with classes on your target items and to traverse the DOM instead of using specific IDs:

<input class='check' type='checkbox' name='cb1' />
<div id="info1">
Hide
</div>



$('.check').click(function(){
    $(this).next().toggle()
})
like image 93
Diodeus - James MacFarlane Avatar answered Jun 24 '26 04:06

Diodeus - James MacFarlane


This places a .change() handler on all the checkboxes where the name attribute starts with cb.

When a change occurs, it traverses to the .next() element sibling, and calls .toggle(), which will show/hide based on whether the checkbox was checked or not.

Example using your HTML: http://jsfiddle.net/fWYtv/

$('input:checkbox[name^=cb]').change(function() {
    $(this).next().toggle( this.checked );
});

EDIT:

Since you stated that there will be over 100 of these, it would really be better to use .delegate(), so you only have one handler instead of 100.

Take the main <div> that is a container for all of the, and give it an ID like container, so you end up with:

<div id='container'>
    <div>
        <input type='checkbox' name='cb1' />
        <div ...

Then call .delegate() on that, and set the input as the target of the event.

Like this:

Example: http://jsfiddle.net/fWYtv/1/

$('#container').delegate('input:checkbox[name^=cb]', 'change', function() {
    $(this).next().toggle( this.checked );
});

This will be a much more efficient way to go.

like image 20
user113716 Avatar answered Jun 24 '26 02:06

user113716



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!