【问题标题】:How can I cancel submit form after password and password confirmation doesn't match密码和密码确认不匹配后如何取消提交表单
【发布时间】:2019-06-20 15:45:52
【问题描述】:

我正在尝试为我的网站做一个注册页面,我不知道如何阻止用户在密码和确认密码不匹配后点击提交。

如果两个密码不匹配,我有一个“警报”功能。

HTML:

<input type="password" name="password" value="" id="password" placeholder="Password">
<input type="password" name="confirm_password" id="confirm_password" placeholder="Confirm Password" onkeyup='check();'/>
span id='message'></span>

JS:

var check = function() {
  if (document.getElementById('password').value ==
    document.getElementById('confirm_password').value) {
    document.getElementById('message').style.color = 'green';
    document.getElementById('message').innerHTML = 'Passwords are matching';
  } else {
    document.getElementById('message').style.color = 'red';
    document.getElementById('message').innerHTML = 'Passwords does not match' ;
  }
}

我在考虑布尔函数,但我不知道如何在里面调用它以及如何取消提交。

【问题讨论】:

标签: javascript html


【解决方案1】:

在您的 JS 中,为什么不将值放入变量中?没必要,但会让 JS 更干净

在该函数 ID 中执行类似

的操作
var password = document.getElementById('password').value
var confrm_password = document.getElementById('confirm_password').value


const button = document.getElementById('button') (Or however you want to target the button, up to you)

并且比 button.disabled = (password === confirm_password))

【讨论】:

    【解决方案2】:

    为您的&lt;form onsubmit="validate()"&gt;添加验证功能

    在提交事件上调用preventDefault 将阻止表单实际提交。

    function validate(event) {
      if (!passesValidation) event.preventDefault();
    }
    

    【讨论】:

      【解决方案3】:

      您可以在密码不匹配时禁用按钮

      document.getElementById("Button").disabled = false;
      

      【讨论】:

      • 我尝试改变这个: document.getElementById('submit').disabled = false;还是不行。
      • 是否还能点击,可以试试换背景看看效果
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-04
      • 2018-05-06
      • 2022-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多