Sometimes we may need to place checks on the input fields before the form is submiteed.
One example is that you may have a re-enter passwork field and if the types passwords are not same, you
may show a error message. In such cases , this is how you can do some work before the form is submitted
and also avoid the submission from happening.
Source
https://stackoverflow.com/questions/8133712/execute-javascript-code-straight-before-page-submit
- Add this attribute to form element.
onsubmit="return checkSame()"
. - Return true or false from checkSame() function for submit/stop-submit.
- You may choose to show a div to display error message to user.
<form class="ui form" action="/users/changePass" method="post" id="pass-form" onsubmit="return checkSame()">
<div class="ui stackable three column grid">
<div class="six wide column t22 text-center">
<div class="text-center"><img src="/images/reset_password.png" height="80"></div>
<div class="clr-sml"></div>
<div class="text-center t18" style="color: #0d71bb"><b>Change Your Password</b></div>
<div class="clr-sml"></div>
<div class="t16 margin-left-right-20 text-center">We maintain your privacy completely by using
encryption so that no one can get into your account..
</div>
</div>
<div class="one wide column"></div>
<div class="eight wide column margin-top-40">
<h4 class="ui dividing header" style="color: #9e1317;font-size: 22px;">Change Password</h4>
<div class="clr-sml"></div>
<div class="clr-sml"></div>
<div class="field">
<input type="password" name="currentpass" placeholder="Enter Current Password" required>
</div>
<div class="field">
<input type="password" name="newpass" id="newpass1" placeholder="Enter New Password" required>
</div>
<div class="field">
<input type="password" id="newpass2" placeholder="Re-Enter New Password" required>
</div>
<div class="clr-sml"></div>
<div class="field text-center">
<button class="ui primary button" type="submit">Submit</button>
</div>
<div class="ui negative message hidden">
<i class="close icon"></i>
<div class="header">
The Passwords you entered do not match !
</div>
<p>Please re-check the values and try again.
</p>
</div>
</div>
</div>
</form>
function checkSame() {
let val1 = $("#newpass1").val();
let val2 = $("#newpass2").val();
console.log(val1, val2);
if (val1 === val2) {
return true;
}
else {
$('.negative.message').removeClass('hidden')
return false;
}
}