javascript - Prevent submission if fields do not match -


i using js check if 2 fields match need way disable submit button if fail match , enable once match:

    <label>new password:</label><br><input type="password" name="new_password"  id="password1"/><br><br>     <label>confirm password:</label><br><input type="password" name="new_password_check"  id="password2" /><br><br>      <p id="validate-status"></p>    $(document).ready(function() {   $("#password2").keyup(validate); });   function validate() {   var password1 = $("#password1").val();   var password2 = $("#password2").val();     if(password1 == password2) {        $("#validate-status").text("passwords match!");             }     else {        $("#validate-status").text("passwords not match!");       }  } 

updated

<form method="post" action="password_change.inc.php">      <input type="hidden" name="user_id" value="<? echo $_session['user_id']; ?>" />       <label>new password:</label><br><input type="password" name="new_password"  id="password1"/><br><br>     <label>confirm password:</label><br><input type="password" name="new_password_check"  id="password2" /><br><br>      <p id="validate-status"></p>         <input id="#submit-button" type="submit" value="change password" /> </form>  <script>  function validate() {     var password1 = $("#password1").val();     var password2 = $("#password2").val();     if(password1 == password2) {          $("#validate-status").text("passwords match!");          $('#submit-button').prop('disabled', false);     }     else {          $("#validate-status").text("passwords not match!");            $('#submit-button').prop('disabled', true);     } }  </script> 

i have updated code per kind suggestion below still allow me post form without disabling until fields match...

you're there. set disabled property on submit button (which appears missing pasted code). assuming submit button has id submit-button:

function validate() {     var password1 = $("#password1").val();     var password2 = $("#password2").val();     if(password1 == password2) {          $("#validate-status").text("passwords match!");          $('#submit-button').prop('disabled', false);     }     else {          $("#validate-status").text("passwords not match!");            $('#submit-button').prop('disabled', true);     } } 

an optimised version "cache" elements so:

var $password1 = $("#password1"),     $password2 = $("#password2"),     $statusmessage = $("#validate-status"),     $submitbutton = $('#submit-button');  function validate() {      if($password1.val() == $password2.val()) {          $statusmessage.text("passwords match!");          $submitbutton.prop('disabled', false);     }     else {          $statusmessage.text("passwords not match!");            $submitbutton.prop('disabled', true);     } } 

Comments