Call jQuery function from different elements

I am new to jQuery, so I hope for help.

I am creating a page with a div that has several checkboxes inside.

Each of these flags is also contained in its own div.

<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 can be captured whenever a flag is clicked (cb1 or cb2) to hide / show it with the corresponding "info" div (info1 or info2).

I will have over 100 flags, so I hope there is a way to do this without having to write more than 100 functions for click ().

Thanks
Mark

+3
source share
5 answers

Try the following:

$("input[type=checkbox]").change(function() {
    var checkID = $(this).attr('name').substr(2);
    $("#info" + checkID).slideToggle("slow");
});

, div display: none;, .

, !

+1

DOM :

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



$('.check').click(function(){
    $(this).next().toggle()
})
+2

a .change() , name cb.

, .next(), .toggle(), / , .

HTML: http://jsfiddle.net/fWYtv/

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

EDIT:

, 100, .delegate(), 100.

<div>, , , container, :

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

Then call.delegate() on this and set the inputevent as the target.

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.

+2
source
$("input[type=checkbox]").click(function(){
  if ( this.checked )
    $(this).next("div").show();
  else
    $(this).next("div").hide();
});
0
source

If you have a large number of flags, consider using delegate for their common ancestor, as this is significantly faster than creating hundreds of event handlers.

0
source

Source: https://habr.com/ru/post/1768691/


All Articles