skip to Main Content

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


  1. Chosen as BEST ANSWER

    I have resolved my problem:

    deleted:

     $('[name="book_active"]').val(data.book_active);
    

    replaced:

    <input name="book_active" type="hidden" value="N">
    <input name="book_active" id="book_active" type="checkbox" role="switch" class="form-check-input" value="Y">
    

    replaced jquery bit:

    if (data.book_active == 'Y') { //check the checkbox
    $('#book_active').prop('checked', true);
    } else {
    $('#book_active').prop('checked', false);
    }
    

  2. 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:

    $('[name="book_active"]').prop("checked", data.book_active == 'Y’)
    

    That will check the checkbox if the value is ‘Y’ and clear it if it is anything else.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search