我想显示一个单选按钮,有它的值提交,但根据情况,它是不可编辑的。Disabled不起作用,因为它不提交值(或者它是否提交?),并且它使单选按钮变灰。只读是我真正想要的,但出于某种神秘的原因,它不起作用。

我是否需要使用一些奇怪的技巧来实现只读以达到预期的效果?我应该用JavaScript写吗?

顺便提一下,有人知道为什么只读在单选按钮中不起作用,而在其他输入标签中却起作用吗?这是HTML规范中不可理解的遗漏之一吗?


当前回答

我发现使用onclick='this。Checked = false;'在一定程度上起了作用。单击的单选按钮将不会被选中。然而,如果有一个单选按钮已经被选中(例如,一个默认值),该单选按钮将变为未选中。

<!-- didn't completely work -->
<input type="radio" name="r1" id="r1" value="N" checked="checked" onclick='this.checked = false;'>N</input>
<input type="radio" name="r1" id="r1" value="Y" onclick='this.checked = false;'>Y</input>

在这种情况下,保持默认值不变并禁用其他单选按钮将保留已经选中的单选按钮,并防止不选中它。

<!-- preserves pre-selected value -->
<input type="radio" name="r1" id="r1" value="N" checked="checked">N</input>
<input type="radio" name="r1" id="r1" value="Y" disabled>Y</input>

这个解决方案并不是防止默认值被更改的最优雅的方法,但无论是否启用javascript,它都是有效的。

其他回答

我正在使用一个JS插件,样式复选框/单选输入元素,并使用以下jQuery来建立一个“只读状态”,其中底层值仍然发布,但输入元素似乎无法访问用户,这是我相信我们将使用只读输入属性的预期原因…

if ($(node).prop('readonly')) {
    $(node).parent('div').addClass('disabled'); // just styling, appears greyed out
    $(node).on('click', function (e) {
        e.preventDefault();
    });
}

这是我的解决方案(覆盖)Sencha ExtJS 7.2+(复选框和单选覆盖)


Ext.define('MyApp.override.field.Checkbox', {
    override: 'Ext.field.Checkbox',

    /**
     * OVERRIDE: to allow updateReadOnly to work propperly
     * @param {boolean} newValue
     *
     * To ensure the disabled state stays active if the field is still readOnly
     * we re - set the disabled state
     */
    updateDisabled(newValue) {
        this.callParent(arguments);

        if (!newValue && this.getReadOnly()) {
            this.inputElement.dom.disabled = true;
        }
    },

    /**
     * OVERRIDE: readonly for radiogroups and checkboxgroup do not work as other fields
     *     https://stackoverflow.com/questions/1953017/why-cant-radio-buttons-be-readonly
     *
     * @param {boolean} newValue
     *
     *  - use disabled on the field
     */
    updateReadOnly(value) {
        this.callParent(arguments);

        if (!this.getDisabled()) {
            this.inputElement.dom.disabled = value;
        }
    }
});

Disabled作用于单个单选按钮(不是整个集合)。 如果您正在使用PHP,并且在浏览器中加载页面之前,服务器上已经知道您的情况,那么您可以使用这个非常简单的解决方案。

<php $chcky= (condition) ? 'checked' : 'disabled';?>
<php $chckn= (condition) ? 'checked' : 'disabled';?>
<input type="radio" name="var" value="Yes" <?php echo $chcky?>></input>
<input type="radio" name="var" value="No" <?php echo $chckn?>></input>

我在响应表单提交的页面上使用它。

尝试禁用属性,但我认为您不会得到单选按钮的值。 或者像这样设置图像:

<img src="itischecked.gif" alt="[x]" />radio button option

致以最亲切的问候。

这是你可以使用的技巧。

<input type="radio" name="name" onclick="this.checked = false;" />