sudip-fullstack
sudip-fullstack

Reputation: 105

jquery next element show hide toggle

here is my html structure

<div class="hide_chk">+ Show Table</div>
<table border="1" class="leads" style="display:none;">
...
</table>

And here is my jquery sample

$(function(){
    $(".hide_chk").on('click',function(){
        $(this).next(".leads").show();
        $(this).addClass("show_chk");
        $(this).removeClass("hide_chk");
        $(this).html("- Hide Table");
    });
    $(".show_chk").on('click',function(){
        $(this).next(".leads").hide();
        $(this).addClass("hide_chk");
        $(this).removeClass("show_chk");
        $(this).html("+ Show Table");
    });
});

The table and div element is multiple, here when I click first the table showing but after next click it is not hiding...

Someone help

Upvotes: 1

Views: 71

Answers (1)

j08691
j08691

Reputation: 207891

You need to use event delegation.

Change:

$(".show_chk").on('click',function(){

to

$(document).on('click','.show_chk',function(){

No .show_chk element exists when the code is executed, so there's nothing for that code to bind to. By using event delegation and binding to an element that exists when the code is executed, the function will work.

Upvotes: 2

Related Questions