【问题标题】:Why can't I use "required" and "disabled" at the same time in radio input field?为什么我不能在无线电输入字段中同时使用“必需”和“禁用”?
【发布时间】:2019-10-14 20:39:52
【问题描述】:

我想在无线电输入字段中添加required 属性,这是我的代码

<!doctype html>
<html>
    <head>
        <meta charset='utf-8'>
        <title>test radio</title>
        <style>
            div.radio{
                background-color:silver;
            }
        </style>
    </head>
    <body>
        <form action='procesPost.html' method='POST'>
            <div class='radio'>
                <input type='radio' required name='test' value=1>
                <input type='radio' required name='test' value=2>
            </div>
            <input type='SUBMIT' value='submit'>
        </form>
    </body>
</html>

效果很好,我必须选择一个无线电来提交,但是,如果我想禁用一个无线电,required 约束将不起作用

<!doctype html>
<html>
    <head>
        <meta charset='utf-8'>
        <title>test radio</title>
        <style>
            div.radio{
                background-color:silver;
            }
        </style>
    </head>
    <body>
        <form action='procesPost.html' method='POST'>
            <div class='radio'>
                <input type='radio' required name='test' value=1>
                <input type='radio' required disabled name='test' value=2>
            </div>
            <input type='SUBMIT' value='submit'>
        </form>
    </body>
</html>

现在,即使我没有选择任何电台,我也可以提交表单。 我想知道为什么会发生这种情况,我该如何解决这个问题?

我在 FierFox 32.0.3、RHEL6.2 中测试了我的代码

【问题讨论】:

  • 因为你已经禁用了这个字段,而不是disabled使用readonly
  • 你试过不把 required 放在禁用的组件上吗?
  • 我在 Firefox 35 中测试了您的第二个代码(逐字),并且尝试在不选择单选按钮的情况下提交表单会导致 HTML5 表单验证消息,说我需要选择其中一个选项。因此,要么 Firefox 32 有一个奇怪的错误,要么在您测试时有其他代码干扰。
  • 删除了我的答案,因为我意识到我无法复制您的问题,只有我的“解决方案”。您是否尝试过从禁用的无线电输入中删除所需的属性? required 属性只需要出现在同一组中的一个单选元素上,整个组都是必需的(即必须选择其中一个选项)。根据规范,元素必须是可变的(即未禁用)才能应用所需的属性。工作小提琴:jsfiddle.net/98a53t9w
  • @PHeiberg 我发现我无法在 Windows、Chrome 中复制这个问题,所以也许它只适用于 Red Hat 中的浏览器,或者它只适用于 Firefox?

标签: html


【解决方案1】:

根据CBroe:

www.w3.org/TR/html5/forms.html#enabling-and-disabling-form-controls:-the-disabled-attribute:

Constraint validation: If an element is disabled, it is barred from constraint validation.

http://www.w3.org/TR/html5/forms.html#barred-from-constraint-validation:

A submittable element is a candidate for constraint validation except when a condition has barred the element from constraint validation.

最后,从约束验证步骤列表中,http://www.w3.org/TR/html5/forms.html#constraint-validation:

3.1: If field is not a candidate for constraint validation, then move on to the next element.

这意味着,当检查表单有效性时,禁用的元素将被“跳过”。

它不会触发任何错误,并且对其所属表单的验证状态没有任何影响。

评论在此链接中。 https://stackoverflow.com/a/30533215

【讨论】:

    猜你喜欢
    • 2022-10-06
    • 2015-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-10
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多