Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't change checkbox state from jquery ajax response

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
    })
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading