为什么单选按钮不能是“只读”的?

发布于 2024-08-16 02:54:10 字数 226 浏览 1 评论 0原文

我想显示一个单选按钮,提交其值,但根据情况,使其不可编辑。禁用不起作用,因为它不提交值(或者提交了?),并且它使单选按钮变灰。只读确实是我正在寻找的,但由于某种神秘的原因它不起作用。

我需要使用一些奇怪的技巧才能使只读功能按预期工作吗?我应该用 JavaScript 来做吗?

顺便说一句,有谁知道为什么只读在单选按钮中不起作用,而在其他输入标签中却起作用?这是 HTML 规范中那些难以理解的遗漏之一吗?

I would like to show a radio button, have its value submitted, but depending on the circumstances, have it not editable. Disabled doesn't work, because it doesn't submit the value (or does it?), and it grays out the radio button. Read-only is really what I'm looking for, but for some mysterious reason it doesn't work.

Is there some weird trick I need to pull to get read-only to work as expected? Should I just do it in JavaScript instead?

Incidentally, does anyone know why read-only doesn't work in radio buttons, while it does work in other input tags? Is this one of those incomprehensible omissions in the HTML specs?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

一生独一 2024-08-23 02:54:10

仅当有其他选项时,单选按钮才需要是只读的。如果您没有任何其他选项,则无法取消选中选中的单选按钮。如果您有其他选项,您可以仅通过禁用其他选项来阻止用户更改值:

<input type="radio" name="foo" value="Y" checked>
<input type="radio" name="foo" value="N" disabled>

Fiddle: http:// jsfiddle.net/qqVGu/

Radio buttons would only need to be read-only if there are other options. If you don't have any other options, a checked radio button cannot be unchecked. If you have other options, you can prevent the user from changing the value merely by disabling the other options:

<input type="radio" name="foo" value="Y" checked>
<input type="radio" name="foo" value="N" disabled>

Fiddle: http://jsfiddle.net/qqVGu/

牵强ㄟ 2024-08-23 02:54:10

我通过仅禁用未选中的单选按钮来伪造单选按钮的只读状态。它可以防止用户选择不同的值,并且选中的值将始终在提交时发布。

使用 jQuery 设为只读:

$(':radio:not(:checked)').attr('disabled', true);

此方法也适用于将选择列表设为只读,只不过您需要禁用每个未选择的选项。

I've faked readonly on a radio button by disabling only the un-checked radio buttons. It keeps the user from selecting a different value, and the checked value will always post on submit.

Using jQuery to make readonly:

$(':radio:not(:checked)').attr('disabled', true);

This approach also worked for making a select list readonly, except that you'll need to disable each un-selected option.

苏佲洛 2024-08-23 02:54:10

这是你可以使用的技巧。

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

This is the trick you can go with.

<input type="radio" name="name" onclick="this.checked = false;" />
回忆凄美了谁 2024-08-23 02:54:10

我有一个很长的表单(250 多个字段),可以发布到数据库。这是一个在线就业申请。当管理员查看已提交的申请时,表单中会填充来自数据库的数据。输入文本和文本区域将替换为它们提交的文本,但单选按钮和复选框对于保留为表单元素非常有用。禁用它们会使它们更难阅读。将 .checked 属性设置为 false onclick 将不起作用,因为填写应用程序的用户可能已经检查了它们。无论如何...

onclick="return false;"

就像“禁用”收音机和复选框的魅力一样。

I have a lengthy form (250+ fields) that posts to a db. It is an online employment application. When an admin goes to look at an application that has been filed, the form is populated with data from the db. Input texts and textareas are replaced with the text they submitted but the radios and checkboxes are useful to keep as form elements. Disabling them makes them harder to read. Setting the .checked property to false onclick won't work because they may have been checked by the user filling out the app. Anyhow...

onclick="return false;"

works like a charm for 'disabling' radios and checkboxes ipso facto.

梨涡少年 2024-08-23 02:54:10

最好的解决方案是设置选中或未选中状态(从客户端或服务器),并且不允许用户在病房后更改它(即使其只读),请执行以下操作:

<input type="radio" name="name" onclick="javascript: return false;" />

The best solution is to set the checked or unchecked state (either from client or server) and to not let the user change it after wards (i.e make it readonly) do the following:

<input type="radio" name="name" onclick="javascript: return false;" />
如何视而不见 2024-08-23 02:54:10

我想出了一种大量使用 javascript 的方法来实现复选框和单选按钮的只读状态。它针对当前版本的 Firefox、Opera、Safari、Google Chrome 以及当前版本和以前版本的 IE(低至 IE7)进行了测试。

为什么不简单地使用您要求的残疾人财产呢?打印页面时,禁用的输入元素以灰色显示。实施此操作的客户希望所有元素都具有相同的颜色。

我不确定我是否可以在这里发布源代码,因为我是在一家公司工作时开发的,但我当然可以分享这些概念。

通过 onmousedown 事件,您可以在单击操作更改选择状态之前读取选择状态。因此,您存储此信息,然后使用 onclick 事件恢复这些状态。

<input id="r1" type="radio" name="group1" value="r1" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);" checked="checked">Option 1</input>
<input id="r2" type="radio" name="group1" value="r2" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);">Option 2</input>
<input id="r3" type="radio" name="group1" value="r3" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);">Option 3</input>

<input id="c1" type="checkbox" name="group2" value="c1" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);" checked="checked">Option 1</input>
<input id="c2" type="checkbox" name="group2" value="c2" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);">Option 2</input>
<input id="c3" type="checkbox" name="group2" value="c3" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);" checked="checked">Option 3</input>

然后,其中的 javascript 部分将像这样工作(同样只是概念):

var selectionStore = new Object();  // keep the currently selected items' ids in a store

function storeSelectedRadiosForThisGroup(elementName) {
    // get all the elements for this group
    var radioOrSelectGroup = document.getElementsByName(elementName);

    // iterate over the group to find the selected values and store the selected ids in the selectionStore
    // ((radioOrSelectGroup[i].checked == true) tells you that)
    // remember checkbox groups can have multiple checked items, so you you might need an array for the ids
    ...
}

function setSelectedStateForEachElementOfThisGroup(elementName) {
    // iterate over the group and set the elements checked property to true/false, depending on whether their id is in the selectionStore
    ...

    // make sure you return false here
    return false;
}

您现在可以通过更改输入元素的 onclick 和 onmousedown 属性来启用/禁用单选按钮/复选框。

I've come up with a javascript-heavy way to achieve a readonly state for check boxes and radio buttons. It is tested against current versions of Firefox, Opera, Safari, Google Chrome, as well as current and previous versions of IE (down to IE7).

Why not simply use the disabled property you ask? When printing the page, disabled input elements come out in a gray color. The customer for which this was implemented wanted all elements to come out the same color.

I'm not sure if I'm allowed to post the source code here, as I developed this while working for a company, but I can surely share the concepts.

With onmousedown events, you can read the selection state before the click action changes it. So you store this information and then restore these states with an onclick event.

<input id="r1" type="radio" name="group1" value="r1" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);" checked="checked">Option 1</input>
<input id="r2" type="radio" name="group1" value="r2" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);">Option 2</input>
<input id="r3" type="radio" name="group1" value="r3" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);">Option 3</input>

<input id="c1" type="checkbox" name="group2" value="c1" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);" checked="checked">Option 1</input>
<input id="c2" type="checkbox" name="group2" value="c2" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);">Option 2</input>
<input id="c3" type="checkbox" name="group2" value="c3" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);" checked="checked">Option 3</input>

The javascript portion of this would then work like this (again only the concepts):

var selectionStore = new Object();  // keep the currently selected items' ids in a store

function storeSelectedRadiosForThisGroup(elementName) {
    // get all the elements for this group
    var radioOrSelectGroup = document.getElementsByName(elementName);

    // iterate over the group to find the selected values and store the selected ids in the selectionStore
    // ((radioOrSelectGroup[i].checked == true) tells you that)
    // remember checkbox groups can have multiple checked items, so you you might need an array for the ids
    ...
}

function setSelectedStateForEachElementOfThisGroup(elementName) {
    // iterate over the group and set the elements checked property to true/false, depending on whether their id is in the selectionStore
    ...

    // make sure you return false here
    return false;
}

You can now enable/disable the radio buttons/checkboxes by changing the onclick and onmousedown properties of the input elements.

冰之心 2024-08-23 02:54:10

对于未选中的单选按钮,将其标记为禁用。这可以防止它们响应用户输入并清除选中的单选按钮。例如:

<input type="radio" name="var" checked="yes" value="Yes"></input>
<input type="radio" name="var" disabled="yes" value="No"></input>

For the non-selected radio buttons, flag them as disabled. This prevents them from responding to user input and clearing out the checked radio button. For example:

<input type="radio" name="var" checked="yes" value="Yes"></input>
<input type="radio" name="var" disabled="yes" value="No"></input>
回忆凄美了谁 2024-08-23 02:54:10

JavaScript 方式 - 这对我有用。

<script>
$(document).ready(function() {
   $('#YourTableId').find('*').each(function () { $(this).attr("disabled", true); });
});
</script>

原因:

  1. $('#YourTableId').find('*') ->这将返回所有标签。

  2. $('#YourTableId').find('*').each(function () { $(this).attr("disabled", true); });
    迭代在此捕获的所有对象并禁用输入标记。

分析(调试):

  1. form:radiobutton 在内部被视为“输入”标签。

  2. 就像上面的 function() 一样,如果您尝试打印 document.write(this.tagName);

  3. 只要在标签中找到单选按钮,它就会返回一个输入标签。

    无论

因此,通过将 * 替换为输入,上面的代码行可以针对单选按钮标签进行更加优化:
$('#YourTableId').find('input').each(function () { $(this).attr("disabled", true); });

JavaScript way - this worked for me.

<script>
$(document).ready(function() {
   $('#YourTableId').find('*').each(function () { $(this).attr("disabled", true); });
});
</script>

Reason:

  1. $('#YourTableId').find('*') -> this returns all the tags.

  2. $('#YourTableId').find('*').each(function () { $(this).attr("disabled", true); });
    iterates over all objects captured in this and disable input tags.

Analysis (Debugging):

  1. form:radiobutton is internally considered as an "input" tag.

  2. Like in the above function(), if you try printing document.write(this.tagName);

  3. Wherever, in tags it finds radio buttons, it returns an input tag.

So, above code line can be more optimized for radio button tags, by replacing * with input:
$('#YourTableId').find('input').each(function () { $(this).attr("disabled", true); });

も星光 2024-08-23 02:54:10

一个相当简单的选项是创建一个在表单的“onsubmit”事件上调用的 JavaScript 函数,以启用单选按钮,以便将其值与表单的其余部分一起发布。
这似乎不是 HTML 规范上的遗漏,而是一种设计选择(一个合乎逻辑的选择,恕我直言),单选按钮不能是只读的,因为按钮不能是只读的,如果你不想使用它,那么禁用它。

A fairly simple option would be to create a javascript function called on the form's "onsubmit" event to enable the radiobutton back so that it's value is posted with the rest of the form.
It does not seem to be an omission on HTML specs, but a design choice (a logical one, IMHO), a radiobutton can't be readonly as a button can't be, if you don't want to use it, then disable it.

时光沙漏 2024-08-23 02:54:10

我发现使用 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,它都会起作用。

I found that use onclick='this.checked = false;' worked to a certain extent. A radio button that was clicked would not be selected. However, if there was a radio button that was already selected (e.g., a default value), that radio button would become unselected.

<!-- 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>

For this scenario, leaving the default value alone and disabling the other radio button(s) preserves the already selected radio button and prevents it from being unselected.

<!-- 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>

This solution is not the most elegant way of preventing the default value from being changed, but it will work whether or not javascript is enabled.

秋风の叶未落 2024-08-23 02:54:10

尝试使用属性disabled,但我认为您将无法获得单选按钮的值。
或者设置图像,例如:

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

致以诚挚的问候。

Try the attribute disabled, but I think the you won't get the value of the radio buttons.
Or set images instead like:

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

Best Regards.

じ违心 2024-08-23 02:54:10

将单选按钮设置为只读非常容易完成。使用 CSS 禁用鼠标选择单选按钮或其标签的功能,并在这些元素上设置 tabindex = -1 以防止用户使用 Tab 键和空格键的组合来选择元素。

input[type="radio"].readonly {
    pointer-events: none;
}

label.readonly {
    pointer-events: none;
}
<input tabindex="-1" class="readonly" type="radio" name="rbgOptions" id="cbOpt1" value="Option1">
<label tabindex="-1" class="readonly" for="cbOpt1">Option 1</label>
<input tabindex="-1" class="readonly" type="radio" name="rbgOptions" id="cbOpt2" value="Option2">
<label tabindex="-1" class="readonly" for="cbIOP">Option 2</label>

Getting radio buttons to be read-only is pretty straightforward to accomplish. Use CSS to disable the ability of the mouse to select the radio button or it's label, and set tabindex = -1 on these elements to prevent the user from using a combination of the tab key and the spacebar to select the elements.

input[type="radio"].readonly {
    pointer-events: none;
}

label.readonly {
    pointer-events: none;
}
<input tabindex="-1" class="readonly" type="radio" name="rbgOptions" id="cbOpt1" value="Option1">
<label tabindex="-1" class="readonly" for="cbOpt1">Option 1</label>
<input tabindex="-1" class="readonly" type="radio" name="rbgOptions" id="cbOpt2" value="Option2">
<label tabindex="-1" class="readonly" for="cbIOP">Option 2</label>

心不设防 2024-08-23 02:54:10

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

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

I'm using a JS plugin that styles checkbox/radio input elements and used the following jQuery to establish a 'readonly state' where the underlying value is still posted but the input element appears inaccessible to the user, which is I believe the intended reason we would use a readonly input attribute...

if ($(node).prop('readonly')) {
    $(node).parent('div').addClass('disabled'); // just styling, appears greyed out
    $(node).on('click', function (e) {
        e.preventDefault();
    });
}
很糊涂小朋友 2024-08-23 02:54:10

这是我针对 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;
        }
    }
});

Here is my solution (override) for Sencha ExtJS 7.2+ (checkbox and radio in a single override)


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;
        }
    }
});
半透明的墙 2024-08-23 02:54:10

禁用适用于单个单选按钮(而不是整个集合)。
如果您使用 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>

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

Disabled works on individual radio buttons (not the whole set).
If you are using PHP and your circumstances are known on the server before loading the page in the browser you can use this very simple solution.

<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>

I use it on the page responding a form submission.

初见你 2024-08-23 02:54:10

摘自https://stackoverflow.com/a/71086058/18183749

如果您无法使用“已禁用”属性(因为它会删除该值的
在 POST 处输入),并注意到 html 属性“readonly”仅有效
在文本区域和一些输入(文本、密码、搜索,据我所知),
最后,如果您不想重复所有内容
选择、复选框和带有隐藏输入的单选,您可能会发现
以下函数或任何您喜欢的内部逻辑:

addReadOnlyToFormElements = function (idElement) {
    // html readonly don't work on input of type checkbox and radio, neither on select. So, a safe trick is to disable the non-selected items
    $('#' + idElement + ' input[type="radio"]:not(:checked)').prop('disabled',true); 

    // and, on the selected ones, mimic readonly appearance
    $('#' + idElement + ' input[type="radio"]:checked').css('opacity','0.5');
}

没有什么比删除这些只读更简单的了

removeReadOnlyFromFormElements = function (idElement) {
    // Remove the disabled attribut on non-selected
    $('#' + idElement + ' input[type="radio"]:not(:checked)').prop('disabled',false); 
 
    // Remove readonly appearance on selected ones
    $('#' + idElement + ' input[type="radio"]:checked').css('opacity','');
}

Extract from https://stackoverflow.com/a/71086058/18183749

If you can't use the 'disabled' attribut (as it erases the value's
input at POST), and noticed that html attribut 'readonly' works only
on textarea and some input(text, password, search, as far I've seen),
and finally, if you don't want to bother with duplicating all your
select, checkbox and radio with hidden input, you might find the
following function or any of his inner logics to your liking :

addReadOnlyToFormElements = function (idElement) {
    // html readonly don't work on input of type checkbox and radio, neither on select. So, a safe trick is to disable the non-selected items
    $('#' + idElement + ' input[type="radio"]:not(:checked)').prop('disabled',true); 

    // and, on the selected ones, mimic readonly appearance
    $('#' + idElement + ' input[type="radio"]:checked').css('opacity','0.5');
}

And there's nothing easier than to remove these readonly

removeReadOnlyFromFormElements = function (idElement) {
    // Remove the disabled attribut on non-selected
    $('#' + idElement + ' input[type="radio"]:not(:checked)').prop('disabled',false); 
 
    // Remove readonly appearance on selected ones
    $('#' + idElement + ' input[type="radio"]:checked').css('opacity','');
}
真心难拥有 2024-08-23 02:54:10

在 JS 中捕获“On_click()”事件并像这里一样检查怎么样?:

http://www.dynamicdrive.com/forums/showthread.php?t=33043

What about capturing an "On_click()" event in JS and checking it like here?:

http://www.dynamicdrive.com/forums/showthread.php?t=33043

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文