我认为他们可以,但我没有把我的钱放在我的嘴(这么说)设置只读属性实际上似乎没有做任何事情。
我宁愿不使用Disabled,因为我希望选中的复选框与表单的其余部分一起提交,我只是不希望客户端能够在某些情况下更改它们。
我认为他们可以,但我没有把我的钱放在我的嘴(这么说)设置只读属性实际上似乎没有做任何事情。
我宁愿不使用Disabled,因为我希望选中的复选框与表单的其余部分一起提交,我只是不希望客户端能够在某些情况下更改它们。
当前回答
最简单的(在我看来):
onclick="javascript:{this.checked = this.defaultChecked;}"
其他回答
我用这个方法得到了如下结果:
<input type=checkbox onclick="return false;" onkeydown="return false;" />
@ (Model.IsEnabled) 使用此条件进行动态检查和取消检查,如果复选框已选中,则设置为只读。
<input id="abc" name="abc" type="checkbox" @(Model.IsEnabled ? "checked=checked onclick=this.checked=!this.checked;" : string.Empty) >
只读对<input type='checkbox'>无效
所以,如果你需要从表单中禁用的复选框中提交值,你可以使用jQuery:
$('form').submit(function(e) {
$('input[type="checkbox"]:disabled').each(function(e) {
$(this).removeAttr('disabled');
})
});
通过这种方式,在提交表单时从元素中删除禁用属性。
我碰巧注意到下面给出的解决方案。在我的研究中发现了同样的问题。 我不知道是谁发的,但不是我做的。它使用jQuery:
$(document).ready(function() {
$(":checkbox").bind("click", false);
});
这将使复选框为只读,这将有助于向客户端显示只读数据。
我会对ConroyP的回答进行评论,但这需要50个声望,而我没有。我确实有足够的声誉来发布另一个答案。对不起。
The problem with ConroyP's answer is that the checkbox is rendered unchangeable by not even including it on the page. Although Electrons_Ahoy does not stipulate as much, the best answer would be one in which the unchangeable checkbox would look similar, if not the same as, the changeable checkbox, as is the case when the "disabled" attribute is applied. A solution which addresses the two reasons Electrons_Ahoy gives for not wanting to use the "disabled" attribute would not necessarily be invalid because it utilized the "disabled" attribute.
假设有两个布尔变量$checked和$disabled:
if ($checked && $disabled)
echo '<input type="hidden" name="my_name" value="1" />';
echo '<input type="checkbox" name="my_name" value="1" ',
$checked ? 'checked="checked" ' : '',
$disabled ? 'disabled="disabled" ' : '', '/>';
如果$checked为true,则复选框显示为选中。如果$checked为false,则该复选框显示为未选中。当且仅当$disabled为false时,用户可以更改复选框的状态。当复选框未选中时,不管用户是否选中,“my_name”参数都不会发布。“my_name=1”参数在复选框被选中时被发布,无论用户是否选中。我相信这就是Electrons_Ahoy一直在寻找的。