HTML
<form action="adduser", method="post">
...
<td colspan="2"><input type="submit" value="Add" onclick="validate()"/></td>
</form>
JavaScript
function validate() {
var payRate = document.getElementById("payRate").value;
if (payRate === parseInt(payRate)) {
alert("it is an integer");
} else {
alert("it is not an integer");
}
在我按下添加按钮后,它调用验证函数,然后调用 servlet(adduser)。我的问题是如何在验证函数中编写代码以防止 servlet 调用。我只想提醒一个对话框并留在页面上。请帮助我
最佳答案
使用事件onSubmit
而不是 onClick
因为用户可以使用回车而不是点击提交按钮。
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
}
如果您需要将表单发送到您的服务器但不需要重新加载页面,请将 return true;
替换为 ajax request .
引用
关于Javascript 停止 servlet 执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23755243/