复选框:通过Ajax更改复选框的状态
问题描述:
我在我的php文件中使用复选框。复选框:通过Ajax更改复选框的状态
<label>
<input type="checkbox" id="response" name="response" value="email">Email
</label>
我正在使用Ajax从数据库检索数据。我想根据数据库数据更改复选框的状态。在数据库中的数据是或。
我可以看到数据从数据库中正常传入,但我不知道如何使用它来更改复选框的状态。
$("#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);
}
})
});
按我的理解$('#response').val(data.response);
将无法正常工作。但不知道我需要放在那里。
谢谢你们。
答
你可以在你的success
回调中使用prop()
方法如下。
success: function (data) {
data = JSON.parse(data);
$('#response').prop('checked', data.response == 1); //add this line
}
它会检查该复选框,如果data.response
是1
,否则取消选中。
答
在您成功功能设置的复选框选中
if(data.response)
$('#response').attr('checked','checked');
虽然使用道具的方法是更好的/真正更新
// new property method
if(data.response)
$('#response').prop('checked', true);
将检查data.response认为,计算结果为真值
对此使用.attr()已弃用,不应使用。 .prop()是正确的解决方案。 “从jQuery 1.6开始,对于尚未设置的属性,.attr()方法返回未定义的值。要检索和更改DOM属性,例如表单元素的checked,selected或disabled状态,请使用.prop()方法。 “ - http://api.jquery.com/attr/ – mhodges