0

I am displaying a checkbox in a modal dialog. I use ajax to retrieve a database model with one of the variables returned being data.admin. When this variable equals the string "A" the checkbox must be shown as checked. Otherwise it should remain unchecked.

Below is my code:

<div class="custom-control custom-checkbox">
       <input type="checkbox" class="custom-control-input" id="admin" name="admin">
       <label class="custom-control-label" for="admin">Admin</label>
</div> 

$(document).on('click', '.edit_data',function(){
    var id_code = $(this).attr("id");
    $.ajax({
        url:"edit.php",
        method:"post",
        data:{id_code:id_code},
        datatype:"json",
        success:function(data){
            $('#code').val(data.code);
            $('#login').val(data.login);
            $('#pass').val(data.pass);
            $('#admin').val(data.admin);
            $('#id_code').val(data.id);
            $('#myModale').modal("show");  
        }
    });
});     

1 Answer 1

1

You can check a checkbox in jQuery by using the prop function:

$('#admin').prop('checked', true); // use false to uncheck

So in your case you'll need to check the variable using an if statement, and then check the checkbox as required:

if(data.admin === "A") {
    $('#admin').prop('checked', true);
}
else {
    $('#admin').prop('checked', false);
}

Use the above the code instead of the line $('#admin').val(data.admin);

EDIT: As Jeto says in a comment below:

Can be shortened to $('#admin').prop('checked', data.admin === 'A');

Sign up to request clarification or add additional context in comments.

1 Comment

Can be shortened to $('#checkbox').prop('checked', data.admin === 'A');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.