Testing123
Testing123

Reputation: 70

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>

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.

Upvotes: 0

Views: 978

Answers (2)

The_Outsider
The_Outsider

Reputation: 1925

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();
    });

}

Upvotes: 1

JSEvgeny
JSEvgeny

Reputation: 2750

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.

Upvotes: 0

Related Questions