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
You must use $("#checkbox") instead of $(this)
"this" cannot work inside "fail" because it refer to ajax function not the changed element
you can also set a variable with "this" and reuse it inside "fail":
Try something like this
Because in the
.fail()
section context$(this)
changes, we cant use it to uncheck the checkboxSo I save the context
$(this)
to the variableself
before, when context$(this)
works with checkbox, and after that use it in the.fail
section