【问题标题】:Invalid input not shown until submitted在提交之前不显示无效输入
【发布时间】:2021-06-11 13:22:48
【问题描述】:

我想让我的 :invalid:required 选择器在提交之前不可见。

我的问题示例如下所示:

input[type=text]:invalid {
    border: red solid 1px;
}
<figure class="fig">
    <label>
        <div class="order">4</div>
        <p>If the Answer to Question 2 is Yes How Many Blocks are
           included (A Form Should be Completed for Each Block)
            <span class="asterisk">&#42;</span>
        </p>
    </label>
    <br>
    <input type="text" name="number_of_blocks"
           placeholder="Enter number of blocks"  
           required="required">
    <br>
</figure>

在我开始填写表格之前,:invalid 伪类已经可见,这看起来不太好。 我怎样才能让它在提交后才可见?

我在这里找到了一些东西:

Form hidden field and required validation use

虽然这不是我要找的,因为它不包含我要搜索的 CSS。

【问题讨论】:

  • 在提交表单时将其设为 input[type=text].submited:invalid {...} 并将 submited 类应用于输入
  • 看起来不错,但是当我提交表单时如何将提交的类应用到输入?
  • 收听您表单上的submit 事件。这是example。当您捕获该事件时,只需将所述类应用于给定形式的所有输入

标签: javascript html css


【解决方案1】:

您必须使用 JavaScript 循环遍历所有输入字段并检查每个字段的有效性。

$('#form').on('submit', function(e) {
  var isValid = true;
  $('input', $(this)).each(function() {
    if (!$(this)[0].checkValidity()) {
      isValid = false;
      $(this).addClass('invalid');
    }
  })
  return isValid;
})
.invalid {
  border: red solid 1px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form" novalidate>
  <figure class="fig">
    <label>
        <div class="order">4</div>
        <p>If the Answer to Question 2 is Yes How Many Blocks are Included (A Form Should be Completed for Each Block)<span class="asterisk">&#42;</span></p>
    </label>
    <br>
    <input type="text" name="number_of_blocks" placeholder="Enter number of blocks" required="required">
    <br>
  </figure>
  <button>Submit form</button>
</form>

【讨论】:

    猜你喜欢
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-13
    • 2018-06-06
    • 2013-09-22
    相关资源
    最近更新 更多