18910140161

JavaScript-如何禁用submit按钮,直到使用html和vanilla JS-Stack Overflow填充所有强制字段

顺晟科技

2022-10-19 13:06:46

79

如何在用户输入所有字段之前禁用提交按钮,以及如何在提交表单上使用事件侦听器。

<form action='index.html' id="form-user" onsubmit="init()">
  <input type="text" name="username" id="username" placeholder="username">
  <input type="email" name="email" id="email" placeholder="email">
  <input type="password" name="password" id="password" placeholder="password">
  <button type="submit" name="submit" id='button-send'>SUBMIT</button>
</form>

jsfiddle链接


顺晟科技:

设置一个带有布尔值的验证对象,以记录所有值是否满足验证。

然后我将遍历所有输入,并为每个输入添加一个事件侦听器。在本例中,我检查了每个字符中是否至少有一个字符,但您可能希望对此展开。

最后,遍历验证对象并检查是否所有值都为true。如果是,则从按钮中删除该属性。

使用onBlur事件将确保用户访问了每个字段。您可能还希望检查字段是否包含值,因此可以添加HTML required属性。

创建一个验证函数,该函数将检查所有验证,并在验证失败时设置按钮的disabled属性,反之亦然。对所有字段的每次更改调用验证函数。

可以使用oninput事件

<form action='index.html' id="form-user" onsubmit="init()">
  <input type="text" name="username" id="username" placeholder="username">
  <input type="email" name="email" id="email" placeholder="email">
  <input type="password" name="password" id="password" placeholder="password">
  <button type="submit" name="submit" id='button-send'>SUBMIT</button>
</form>

这可能不是您想要的,但只需在输入字段中使用属性就可以达到几乎相同的效果:

  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航