简体   繁体   中英

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

I have this javascript below:

 <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:

    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. 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:

 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. Also don't forget to set disabled to 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"/> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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