Home > Enterprise >  Can't change checkbox state from jquery ajax response
Can't change checkbox state from jquery ajax response

Time:09-14

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

CodePudding user response:

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

CodePudding user response:

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

  • Related