简体   繁体   English

如何禁用提交按钮,直到Javascript中的密码字段匹配?

[英]How to disable submit button until the password fields are matching in Javascript?

I have this javascript below: 我在下面有这个javascript:

 <script type="text/javascript">

    function PassCheck() {

    var password = document.getElementById('password');
    var vpassword = document.getElementById('vpassword');

    if(password.value!= vpassword.value){
        document.getElementById("button1").disabled = true;  
    }
        }  

</script>

HTML code: HTML代码:

    Password: <input type="password" name="password" id="password" required onchange='PassCheck();'/> <br>
    Verify Password: <input type="password" name="vpassword" required id="vpassword" onchange='PassCheck();'/> <br>
  <input type="submit" value="Submit" id="button1" name="submit" onchange='PassCheck();'/>

The submit button is disabled only the first time and the disbale button doesn't work after second attempt. 提交按钮仅在第一次被禁用,并且disbale按钮在第二次尝试后不起作用。 I am not sure why its not working. 我不确定为什么它不起作用。 Please help! 请帮忙! Thanks in advance. 提前致谢。

You simply need to add an else condition that re-enables your button once the values match: 您只需要添加一个else条件,一旦值匹配,即可重新启用您的按钮:

 function PassCheck() { var password = document.getElementById('password'); var vpassword = document.getElementById('vpassword'); if (password.value != vpassword.value) { document.getElementById("button1").disabled = true; } else { document.getElementById("button1").disabled = false; } } 
 Password: <input type="password" name="password" id="password" required onchange='PassCheck();' /> <br> Verify Password: <input type="password" name="vpassword" required id="vpassword" onchange='PassCheck();' /> <br> <input type="submit" value="Submit" id="button1" name="submit" onchange='PassCheck();' /> 

onchange occurs only when the element loses focus, so try to use onkeyup or oninput events. 仅当元素失去焦点时才会发生onchange ,因此请尝试使用onkeyuponinput事件。 Also don't forget to set disabled to false . 同样不要忘记将disabled设置为false

 function PassCheck() { var password = document.getElementById('password'); var vpassword = document.getElementById('vpassword'); document.getElementById("button1").disabled = password.value.length === 0 || password.value != vpassword.value; } PassCheck(); 
 Password: <input type="password" name="password" id="password" required onkeyup='PassCheck();'/> <br> Verify Password: <input type="password" name="vpassword" required id="vpassword" onkeyup='PassCheck();'/> <br> <input type="submit" value="Submit" id="button1" name="submit"/> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM