我认为他们可以,但我没有把我的钱放在我的嘴(这么说)设置只读属性实际上似乎没有做任何事情。

我宁愿不使用Disabled,因为我希望选中的复选框与表单的其余部分一起提交,我只是不希望客户端能够在某些情况下更改它们。


当前回答

这是一个不能更改的复选框:

<input type="checkbox" disabled="disabled" checked="checked">

只需添加disabled="disabled"作为属性。

编辑以处理评论:

如果你想要数据被返回,那么一个简单的解决方案是将相同的名称应用到隐藏的输入:

<input name="myvalue" type="checkbox" disabled="disabled" checked="checked"/>
<input name="myvalue" type="hidden" value="true"/>

这样,当复选框被设置为“禁用”时,它只服务于数据的可视化表示,而不是实际“链接”到数据。在回发中,当复选框被禁用时,隐藏输入的值将被发送。

其他回答

READONLY对复选框不起作用,因为它阻止你编辑字段的值,但有了复选框,你实际上是在编辑字段的状态(在||关闭)

从faqs.org:

READONLY只是阻止用户更改字段的值,而不是阻止用户与字段交互,理解这一点很重要。例如,在复选框中,您可以打开或关闭复选框(从而设置CHECKED状态),但不能更改字段的值。

如果不想使用disabled,但仍然想提交值,那么当值不满足编辑条件时,将值作为隐藏字段提交并将其内容打印给用户如何?如。

// user allowed change
if($user_allowed_edit)
{
    echo '<input type="checkbox" name="my_check"> Check value';
}
else
{
    // Not allowed change - submit value..
    echo '<input type="hidden" name="my_check" value="1" />';
    // .. and show user the value being submitted
    echo '<input type="checkbox" disabled readonly> Check value';
}

不,但是您可以使用javascript事件来实现类似的功能

我只是不希望客户在某些情况下能够更改它们。

READONLY本身不起作用。你可能可以用CSS做一些奇怪的事情,但我们通常只是禁用它们。

警告:如果它们被发布回来,那么客户端可以更改它们,句号。你不能依靠只读来阻止用户修改某些东西。总是可以使用fiddler或只是改变html w/firebug或诸如此类的东西。

迟来的回答,但大多数答案似乎过于复杂了。

据我所知,OP的基本要求是:

只读复选框显示状态。 随form返回的值。

应当指出的是:

The OP preferred not to use the disabled attribute, because they 'want the checked check boxes to be submitted with the rest of the form'. Unchecked checkboxes are not submitted with the form, as the quote from the OP in 1. above indicates they knew already. Basically, the value of the checkbox only exists if it is checked. A disabled checkbox clearly indicates that it cannot be changed, by design, so a user is unlikely to attempt to change it. The value of a checkbox is not limited to indicating its status, such as yes or false, but can be any text.

因此,由于readonly属性不起作用,不需要javascript的最佳解决方案是:

禁用的复选框,没有名称或值。 如果复选框要显示为已选中,则会显示存储在服务器上的具有名称和值的隐藏字段。

对于选中的复选框:

<输入类型=“复选框” 选中=“选中” 禁用=“禁用” /> <输入类型=“隐藏” 名称=“字段名称” 值=“字段值” />

对于未选中的复选框:

<输入类型=“复选框”禁用=“禁用” />

禁用输入的主要问题,特别是复选框,是它们的对比度差,这可能是一些视觉障碍的问题。用简单的词来表示值可能会更好,比如Status: none或Status: implemented,但在使用后者时包含上面的隐藏输入,比如:

<p>状态:执行<输入类型=“隐藏”

基于以上答案,如果使用jQuery,这可能是所有输入的一个很好的解决方案:

<script>
    $(function () {
        $('.readonly input').attr('readonly', 'readonly');
        $('.readonly textarea').attr('readonly', 'readonly');
        $('.readonly input:checkbox').click(function(){return false;});
        $('.readonly input:checkbox').keydown(function () { return false; });
    });
</script>

我对Asp使用这个。Net MVC设置一些表单元素为只读。通过将任何父容器设置为.readonly,上述方法适用于文本和复选框,例如以下场景:

<div class="editor-field readonly">
    <input id="Date" name="Date" type="datetime" value="11/29/2012 4:01:06 PM" />
</div>
<fieldset class="flags-editor readonly">
     <input checked="checked" class="flags-editor" id="Flag1" name="Flags" type="checkbox" value="Flag1" />
</fieldset>