I have a simple table with a checkbox in one table cell – when the user clicks the checkbox it calls a script which calls a php file to make some database updates. This is all working well.
If there’s an error with the php script or it returns an error I would like to restore the checkbox to its original checked state before the user clicked on it. I thought the following would do this but it’s making any change:
if (checkedState === 'true') {
$this.attr('checked', false);
} else {
$this.attr('checked', true);
}
I’ve attached the full script which works except for the above part where it attempts to restore the checkbox to it’s original checked state.
$(document).ready(function() {
$("input.select-item").click(function() {
//console.log( 'starting Checklist Item Update' );
var recid = $(this).closest('td').attr('id');
var checkedState = $(this).is(":checked");
// Create a reference to $(this) here:
$this = $(this);
$.post('updateItem.php', {
type: 'updateItem',
recid: recid,
selectionType: checkedState
}, function(data) {
data = JSON.parse(data);
//console.log( data );
if (data.error) {
var ajaxError = (data.text);
var errorAlert = 'There was an error updating the Completed Checklist Item - ' + ajaxError + '. Please contact the Developer';
$this.closest('td').addClass("table-danger");
// Restore checkbox to it's original state
if (checkedState === 'true') {
$this.attr('checked', false);
} else {
$this.attr('checked', true);
}
//display AJAX error details
$("#updateSelectionsErrorMessage").html(errorAlert);
$("#updateSelectionsError").show();
return; // stop executing this function any further
} else {
$this.closest('td').addClass("table-success")
$this.closest('td').removeClass("table-danger");
// Restore checkbox to it's original state
if (checkedState == true) {
$this.attr('checked', false);
} else {
$this.attr('checked', true);
}
}
}).fail(function(xhr) {
var httpStatus = (xhr.status);
var ajaxError = 'There was an error updating the Completed Checklist Item - AJAX request error. HTTP Status: ' + httpStatus + '. Please contact the Developer';
$this.closest('td').addClass("table-danger");
//display AJAX error details
$("#updateSelectionsErrorMessage").html(ajaxError);
$("#updateSelectionsError").show();
$this.attr('checked', false); // Unchecks it
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<table class="table table-striped table-hover table-bordered">
<thead>
<th style="width: 20%" scope="col">Category</th>
<th style="width: 60%" scope="col">Description</th>
<th style="width: 10%" scope="col">Completed</th>
<th style="width: 10%" scope="col">Check</th>
</thead>
<tbody>
<tr id="1">
<td>Main</td>
<td>Lorem ipsum dolor sit amet</td>
<td>1</td>
<td id="1"><input type="checkbox" class="select-item checkbox" name="select-item" value="1"></td>
</tr>
</tbody>
</table>