Reputation: 3986
I am using checkbox in my php file.
<label>
<input type="checkbox" id="response" name="response" value="email">Email
</label>
I am retrieving the data from database by using Ajax. I want to change the state of checkbox as per the database data. In database data are 0 or 1.
I can see data is coming properly from database but i don't know how can i use that to change state of checkbox.
$("#autofill").change(function () {
$.ajax({
type: "GET",
url: "autofill.php",
cache: false,
// dataType: 'json',
data: 'action1=' + data1,
success: function (data) {
data = JSON.parse(data);
$('#response').val(data.response);
}
})
});
As per my understanding $('#response').val(data.response);
will not work. But not sure what do i need to put there.
Thanks guys.
Upvotes: 2
Views: 2964
Reputation: 4488
On your success function set the checkbox to checked
if(data.response)
$('#response').attr('checked','checked');
Though using the prop method is better/newer really
// new property method
if(data.response)
$('#response').prop('checked', true);
Will check if data.response holds a value that evaluates to true
Upvotes: 3
Reputation: 20740
You can use prop()
method like following in your success
callback.
success: function (data) {
data = JSON.parse(data);
$('#response').prop('checked', data.response == 1); //add this line
}
It will check the checkbox if data.response
is 1
, otherwise uncheck.
Upvotes: 3