简体   繁体   中英

Button click function not being called the second time of button click

I have an MVC application and one of the views contains a button with a condition.

<a href="#DidNotEatModal" role="button" class="btn btnDidNotEat" data-toggle="modal"><i class="fa fa-sticky-note-o"></i>Did Not Eat</a>   

<button type="button" id="btnRemoveDidNotEat" class="btn btnRemoveDidNotEat">Remove Did Not Eat</button>
  • On click of btnRemoveDidNotEat,btnRemoveDidNotEat is hidden.
  • If btnDidNotEat is clicked,btnRemoveDidNotEat is shown.

Here is my JS code.

    $('.btnDidNotEat').on('click', function () {   
        $.ajax({

        }).done(function (partialViewResult) {        
            $('#btnRemoveDidNotEat').show();
        });
    });


    $('#btnRemoveDidNotEat').on('click', function () {   
        $.ajax({     

        }).done(function (partialViewResult) {                       
            $('#btnRemoveDidNotEat').hide();
        });
    });

The functionality works for the first time. On click of ".btnDidNotEat", the other button '#btnRemoveDidNotEat' is shown. On click of '#btnRemoveDidNotEat', it is hidden as required.

However the second time,On click of ".btnDidNotEat", the other button '#btnRemoveDidNotEat' is shown. But the button click function for '#btnRemoveDidNotEat' is not called.

I have tried doing the same with style="display:none;", but that gives me the same issue. I have also tried using toggle.

Am I missing something?

EDIT : Simplified the question to make it more clear.

I am not sure I understand your question right, but it looks like your AJAX response seems to have a partial view result. If you are trying to access the button click event of that partial view of AJAX, it will not hit the click event because it will not be attached to the DOM. So instead of your code, you should use something like this.

$("body").on("click", ".btnRemoveDidNotEat", function() {
    $.ajax({     

    }).done(function (partialViewResult) {                       
        $('#btnRemoveDidNotEat').hide();
    });

}

I'm not sure if I understood your question correctly, but here is what I got fiddle

Here is some improvements of your script:

$('.btnDidNotEat').click(function () {   
    $.ajax({

    }).done(function (partialViewResult) {        
        $('#btnRemoveDidNotEat').toggle();
    });
});


$('#btnRemoveDidNotEat').click(function () {   
    $.ajax({     

    }).done(function (partialViewResult) {                       
        $('#btnRemoveDidNotEat').toggle();
    });
});

You can use toggle() function instead of adding and deleting class.

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