我已经尝试了所有可能的方法,但仍然无法正常工作。
我有一个带有 checkbox
的模态窗口 我希望当模态打开时,checkbox
选中或取消选中应该基于数据库值。 (我已经与其他表单字段一起使用了。)我开始尝试检查它,但没有用。
我的 HTML 分区:
<div id="fModal" class="modal" >
...
<div class="row-form">
<div class="span12">
<span class="top title">Estado</span>
<input type="checkbox" id="estado_cat" class="ibtn">
</div>
</div>
</div>
和 jQuery:
$("#estado_cat").prop( "checked", true );
我也尝试过使用 attr
和论坛中看到的其他方法,但似乎都不起作用。
有人能给我指出正确的方法吗?
编辑
好吧,我真的错过了一些东西。如果复选框在页面中,我可以使用代码选中/取消选中,但如果它在模态 窗口中,我不能。我尝试了几十种不同的方法。
我有一个可以打开模式的链接:
<a href='#' data-id='".$row['id_cat']."' class='editButton icon-pencil'></a>
和 jQuery 来“监听”点击并执行一些操作,比如用来自数据库的数据填充一些文本框。一切都像我想要的那样工作,但问题是我无法使用代码设置复选框选中/未选中。请帮忙!
$(function () {
$(".editButton").click(function () {
var id = $(this).data('id');
$.ajax({
type: "POST",
url: "process.php",
dataType: "json",
data: {
id: id,
op: "edit"
},
}).done(function (data) {
// The next two lines work fine,
// i.e. it grabs the value from database and fills the textboxes
$("#nome_categoria").val(data['nome_categoria']);
$("#descricao_categoria").val(data['descricao_categoria']);
// Then I tried to set the checkbox checked (because it's unchecked by default)
// and it does not work
$("#estado_cat").prop("checked", true);
$('#fModal').modal('show');
});
evt.preventDefault();
return false;
});
});
最佳答案
你必须使用'prop'函数:
.prop('checked', true);
jQuery 1.6 之前(参见 user2063626's answer ):
.attr('checked','checked')
关于jQuery 设置复选框已选中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15044340/