irwan dwiyanto irwan dwiyanto - 9 days ago 5
Ajax Question

Issue with check/uncheck Radio button based on condition using jQuery

I am trying to retrieve the value of ajax and it worked, but I try want to display input: radio if the condition is true then it will be checked, but no change in my script.
so if the value status = 1, then input: radio is checked and if the value status = 0 then it is not checked.

My Html

<div class="col-md-6">
<label for="status">Status</label>
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default btn-on btn-sm ">
<input type="radio" value="0" name="status" id="aktif" >Active</label>
<label class="btn btn-default btn-off btn-sm active">
<input type="radio" value="1" name="status" id="deaktif" >Deactive</label>
</div>
</div>


My ajax

$.ajax({
url : "<?php echo site_url('edit')?>/" + id_user,
type: "GET",
dataType: "JSON",
success: function(data) {
$('[name="status"]').val(data.msg_activation);
$('#edit').modal('show');

if($('[name="status"]').val(data.status) === 1) {
$('#aktif').prop('checked', true);
}
},
error: function (jqXHR, errorThrown) {
alert('Error ajax');
}
});

Answer

Remove the if condition and try as below,

$('#aktif').prop('checked', data.status === 1);

Code

$.ajax({
    url : "<?php echo site_url('edit')?>/" + id_user,
    type: "GET",
    dataType: "JSON",
    success: function(data) {
        $('[name="status"]').val(data.msg_activation);
        $('#edit').modal('show'); 

        $('div.btn-group label.btn').removeClass('btn-on btn-off');

        $('#aktif').prop('checked', data.status === 1);
        $('#aktif').parent().addClass(data.status === 1 ? 'btn-on' ? 'btn-off');

        $('#deaktif').prop('checked', data.status === 0);
        $('#deaktif').parent().addClass(data.status === 0 ? 'btn-on' ? 'btn-off');
    },
    error: function (jqXHR, errorThrown) {
        alert('Error ajax');
    }
}); 
Comments