Peter
Peter

Reputation: 9113

Weird behavior while using replaceWith() in jQuery

I'm having some trouble in using jQuery. I'm trying to do an AJAX request and change the clicked element if that request gives the correct response.

My jQuery:

$(document).on('click', '.add-to-check', function (e) {
    e.preventDefault();
    var url = $(this).attr('href');
    $.ajax({
        url: url,
        type: "GET",
        success: function (response) {
            var result = jQuery.parseJSON(response);
            if (result.status == 'success') {
                $(e.target).replaceWith('<i class="fa fa-check"></i>');
            } else if (result.status == 'failure') {
                // failure
            }
        },
    });
    return false;
});

My HTML:

<a class="btn btn-sm btn-primary pull-left add-to-check" href="/tasks/check/1235"><i class="fa fa-close"></i></a>

This doesn't properly work however. When I click the button, most of the times the button disappears as it should and a check icon shows up. This is the way it should be working.

Sometimes, however: The check mark shows up but it is still a button. And I cannot figure out why this is.

Upvotes: 0

Views: 58

Answers (2)

koressak
koressak

Reputation: 191

Other approach is to have pre-generated and hidden the successful icon element (for example with class sucess).

When you get to the successful response from server (as the task has been completed) you just hide the link element and show the successful icon.

Upvotes: 0

Rudi
Rudi

Reputation: 2995

Try it this way:

$(document).on('click', '.add-to-check', function (e) {
e.preventDefault();
var $this = $(this);
var url = $this.attr('href');
$.ajax({
    url: url,
    type: "GET",
    success: function (response) {
        var result = jQuery.parseJSON(response);
        if (result.status == 'success') {
            $this.replaceWith('<i class="fa fa-check"></i>');
        } else if (result.status == 'failure') {
            // failure
        }
    },
});
return false;

});

Upvotes: 1

Related Questions