Reputation: 203
<form action="adduser", method="post">
...
<td colspan="2"><input type="submit" value="Add" onclick="validate()"/></td>
</form>
function validate() {
var payRate = document.getElementById("payRate").value;
if (payRate === parseInt(payRate)) {
alert("it is an integer");
} else {
alert("it is not an integer");
}
After i press the add button, it call the validate function, then it call the servlet(adduser). My question is how to i write the code in validate function to prevent the servlet calling. I just want to alert a dialog box and stay remains on the page. Please help me
Upvotes: 1
Views: 635
Reputation: 12864
Use the event onSubmit
instead of onClick
because the user can use enter instead of clicking on the submit button.
HTML :
<form action="adduser", method="post" onsubmit="return validate();">
...
<td colspan="2"><input type="submit" value="Add"/></td>
</form>
Javascript :
function validate() {
var payRate = document.getElementById("payRate").value;
if (payRate === parseInt(payRate)) {
alert("It is an integer");
return true; // return true if you want to send the form to your server and reload the page
} else {
alert("It is not an integer");
}
return false; // return false to not reload the page
}
If you need to send the form to your server but not reload the page, replace return true;
by an ajax request.
Reference
Upvotes: 4
Reputation: 382
If you need to inform you have to return false or true on your validate method in javascript when you click(onClick event):
<form action="adduser", method="post">
...
<td colspan="2"><input type="submit" value="Add" onclick="return validate();"/></td>
</form>
And return true if input is correct or false otherwise if I understand correctly what you want to perform(informing of incorrect data submitted):
function validate() {
var payRate = document.getElementById("payRate").value;
if (payRate === parseInt(payRate)) {
alert("it is an integer");
return true;
} else {
alert("it is not an integer");
return false;
}
in this way if data is correct the user is informed with alert() and the request is sent to the server otherwise the user is informed of incorrect data and no submit is send to server as long as you return false in the validate function.
Upvotes: 2
Reputation: 18566
function validate() {
var payRate = document.getElementById("payRate").value;
if (payRate === parseInt(payRate)) {
alert("it is an integer");
} else {
alert("it is not an integer");
}
return false; // this will disable the function
}
In HTML, make the following changes :
<td colspan="2"><input type="submit" value="Add" onclick="return validate()"/></td>
Upvotes: 2