【问题标题】:Required function is not working in HTML form所需功能在 HTML 表单中不起作用
【发布时间】:2019-05-23 15:56:38
【问题描述】:

我已经在 HTML <Select> 中应用了 <Required> 标记,但无法正常工作。即使在第一步没有选择任何内容,表单仍然可以继续下一步。有谁知道解决吗?

    <label>Region :</label>
    <select id="Region" class="custom-select form-control" required>
    <option value="">Select Region</option>
    <option value="central" id="Central">Central</option>
    <option value="northern" id="Northern">Northern</option>
    </select>

【问题讨论】:

  • 我预计这是由于 Select Region 默认被选中,因为它具有非值。就表单而言,它是一个有效的选项,因此 required 指标已得到满足
  • 那么如何让选择默认为取消选择呢?任何想法? :-)
  • 我建议您在提交之前使用表单验证和 Javascript 来验证输入。就像 Martin 上面所说的,当默认选择“选择区域”时,“必填”指示符得到满足。
  • 也许您可以用标签替换“选择区域”,而不是像 Martin 所说的那样不给它任何值,默认情况下它会自动满足。
  • 你的意思是这样吗? &lt;option value=""&gt;&lt;label&gt;Select Region&lt;/label&gt;&lt;/option&gt;

标签: html required


【解决方案1】:

您是否使用 HTML5 声明了您的网页?确保在页面开头声明以下语句

<!DOCTYPE html>

required 属性仅在 HTML5 中可用,并且仅受特定浏览器支持...w3schools Required Attribute

已经在 HTML5 中测试了您的原始代码,它可以工作。

【讨论】:

    【解决方案2】:

    您可以完全摆脱选择选项标签,并将值select option 放在选择标签本身中。

    <label>Region:</label>
    <select value="Select Option" id="Region" class="custom-select form- control" required>
    
    <option value="central" id="Central">Central</option>
    <option value="northern" id="Northern">Northern</option>
    </select>
    

    【讨论】:

    • 我也试过&lt;option disable&gt;Select Region&lt;/option&gt;,但Select Region还是默认选中的。
    • 您是否可以将其设为标签而不是将其放入下拉列表中?那会好吗?因为当您可以通过标签提示用户时,担心那么小的事情似乎毫无意义。不要批评。
    【解决方案3】:

    您的代码是否有效取决于您使用的浏览器或您使用它的方式。我为你写了一个示例代码。希望对你有帮助:

    <!DOCTYPE html>
    <html>
    <body>
    <form >
     <label>Region :</label>
        <select id="Region" class="custom-select form-control" required>
        <option value="">Select Region</option>
        <option value="central" id="Central">Central</option>
        <option value="northern" id="Northern">Northern</option>
        </select>
      <input type="submit">
    </form>
    </body>
    </html>

    所以在上面的代码中如果你不选择任何东西它不会让你提交。

    【讨论】:

      猜你喜欢
      • 2013-09-12
      • 1970-01-01
      • 2017-11-07
      • 2020-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      相关资源
      最近更新 更多