I store details about books in table called books. One of the columns is called "book_active" and holds values "Y" or "N".
I want my checkbox named "book_active" to be checked if value in mentioned column equals "Y" and unchecked if value equals "N".
Currently after sending the form the value of that checkbox is "NULL" in database. I’m stuck how to approach this.
<input name="book_active" id="book_active" type="checkbox" role="switch" class="form-check-input" value="Y">
<script>
function edit_book(id) {
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
$.ajax({ //Load data from ajax
url: "<?php echo site_url('book/ajax_edit/') ?>" + id,
type: "GET",
dataType: "JSON",
success: function(data) {
$('[name="book_active"]').val(data.book_active);
//selecting checkbox - doesnt work
if (data.book_active == 'Y') {
$('#book_active').prop('checked', data.book_active == 'Y'); //.prop (name, value)
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
})
}
</script>
2
Answers
I have resolved my problem:
deleted:
replaced:
replaced jquery bit:
Your description of the goal, “If equals ‘Y’ checkbox should be checked and if not, checkbox value should be ‘N’.” is a little confusing. If you want to set the checkbox’s state depending on the value of
data.book_active
, this ought to do it:That will check the checkbox if the value is ‘Y’ and clear it if it is anything else.