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");
}
在我按下add按钮之后,它调用validate函数,然后调用servlet(adduser)。我的问题是如何在validate函数中编写代码以防止servlet调用。我只想提醒一个对话框并保持在页面上。请帮帮我
最佳答案
使用事件onSubmit
而不是onClick
,因为用户可以使用enter而不是单击submit按钮。
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
}
如果需要将表单发送到服务器但不重新加载页面,请用ajax request替换
return true;
。参考
MDN onSubmit
MDN onClick
MDN AJAX