简体   繁体   中英

Javascript Show Hide input not working the second time bootstrap modal is loaded

I have a JavaScript code to hide and show an upload input using a checkbox inside a bootstrap modal, it is working when modal is fired up the first time, but on the second i open the modal, and click on the checkbox to show the upload input, it shows but then it automatically hides it.

$('.modal').on('loaded.bs.modal', function (e) {        
    $(".upload_file").hide();
    $(".show_hide").show();

    $('.show_hide').click(function(){
        $(".upload_file").slideToggle();    
    });

       //jquery validation goes here...
}); 

What am i missing here, hope you guys can help. TIA.

You are creating multiple click events, every time you open the modal it creates a new one.

Change

$('.show_hide').click(function(){
    $(".upload_file").slideToggle();    
});

to

$('.show_hide').off('click').on('click', function(){
    $(".upload_file").slideToggle();    
});

This will kill the first click event, and then rebind it.

Alternatively you could move the binding for the click event out of the modal initialisation so it only gets called once.

$('body').on('click','.show_hide',function(){
    $(".upload_file").slideToggle();    
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM