I am struggling to change the toggle checkbox to previous state(based on the ajax result). If my ajax result is "false" then I want it go to previous state. Because ajax is called after user click the toggle. And once user clicks state is changing and only after that I am doing ajax control.
Html code block is:
<form method="post" id="toggleForm_{{$detail['id']}}">
<input data-id="{{$detail['id']}}" id="{{$detail['id']}}" class="toggle-class" type="checkbox" data-onstyle="success" data-offstyle="danger" data-toggle="toggle" data-on="Active" data-off="InActive" {{ $detail['status'] == 1 ? 'checked' : '' }}>
<input type="hidden" class="statusForDetail" value="{{$detail['id']}}" page="sections-set-status" >
</form>
and my jQuery is :
function onToggle() {
var page = $(".statusForDetail").attr('page');
$(".statusForDetail").each((index, element) => {
let id = $(element).val();
let sid = $(element).val();
$('#toggleForm_'+id).find('input[type="checkbox"]').change(function () {
this.checked ? updateStatus(1,id, page,sid): updateStatus(0,id, page,sid);
});
});
}
function updateStatus(status_val,id, page,sid) {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "POST",
url: "/admin/" + page,
data: {status: status_val, id: id},
success: function (result) {
if (result[0] == "Success!") {
if (status_val == 1) {
$("#updatedAt").fadeIn(0).html("<font color='green' font size='2px'> : "+ result[0] + result[1] +"</font>").fadeOut(1500);
} else if (status_val == 0) {
$("#updatedAt").fadeIn(0).html("<font color='green' font size='2px'> : "+ result[0] + result[1] +"</font>").fadeOut(1500);
}
} else {
if (status_val == 1) {
$("#updatedAt").fadeIn(0).html("<font color='red'>" + result[0] + result[1] + "</font>").fadeOut(1500);
$('#toggleForm_'+sid).prop('checked', false);
} else if (status_val == 0) {
$("#updatedAt").fadeIn(0).html("<font color='red'>" + result[0] + result[1] + "</font>").fadeOut(1500);
$('#toggleForm_'+sid).prop('checked', true);
}
}
}, error: function () {
}
});
}
as you see I am sending data to my php and according to the result I am making toggle on or off. but the line :
$('#toggleForm_'+sid).prop('checked', false);
does not work at all. The state does not change in my html page. even I am getting "false"
from php it changes to on or off respectively. However, when I get the "false"
result from php I want switch to go to previous state (because user pressed the toggle and it’s state has been changed already until ajax part).
Any help would be highly appreciated.
4
Answers
could pass or set a reference of the checkbox that probably be easier, something like:
or
there is also a bind method too
it should be something like this for custom toggle
and then in the part where you passed or set the reference to the checkbox
are you able to knock up a jsfiddle as hard to help based off partial code/html?
something like this hopefully: