skip to Main Content

I am trying to change the state of the checkbox in case the request fails. But it won’t change it from inside the fail function of jquery’s ajax:

$('.checkbox').on('change', function () {
    let checked = $(this).is(':checked');

    var jqxhr = $.ajax({
        // ajax parameters
    })
    .done(function () {
    })
    .fail(function () {
        $(this).prop('checked', !checked);
    })
});

When I use $(this).prop('checked', !checked); outside the fail and inside the on('change'.., it works.

I even tried to log the content of $(this) and checked in the scope of the fail function and it looks like it does get the checkbox element and the value

2

Answers


  1. You must use $("#checkbox") instead of $(this)

    "this" cannot work inside "fail" because it refer to ajax function not the changed element

    $('#checkbox').on('change', function () {
        let checked = $(this).is(':checked');
    
        var jqxhr = $.ajax({
            // ajax parameters
        })
        .done(function () {
        })
        .fail(function () {
            $("#checkbox").prop('checked', !checked);
        })
    });
    

    you can also set a variable with "this" and reuse it inside "fail":

    $('.checkbox').on('change', function () {
        let checked = $(this).is(':checked');
        let _this = this;
        var jqxhr = $.ajax({
            // ajax parameters
        })
        .done(function () {
        })
        .fail(function () {
            $(_this).prop('checked', !checked);
        })
    });
    
    Login or Signup to reply.
  2. Try something like this

    $('.checkbox').on('change', function () {
        let self = $(this);
        let checked = $(this).is(':checked');
        
    
        var jqxhr = $.ajax({
            // ajax parameters
        })
        .done(function () {
        })
        .fail(function () {
            self.prop('checked', !checked);
        })
    });
    

    Because in the .fail() section context $(this) changes, we cant use it to uncheck the checkbox
    So I save the context $(this) to the variable self before, when context $(this) works with checkbox, and after that use it in the .fail section

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search