2011-08-17 170 views
2

我试图找到任何有用的帖子为我的问题,但没有找到如此我的问题: 我想验证表单之前提交到数据库。这是我的代码:使用onsubmit验证表单使用Javascript不起作用

<%@ page language="java" contentType="text/html; charset=windows-1255" 
pageEncoding="windows-1255"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=windows-1255"> 
<title>Registration</title> 
<link rel="shortcut icon" href="img/icon0.png" /> 
<link rel="stylesheet" type="text/css" href="../css/index.css" /> 
<script type="text/javascript"> 
function validate_form() 
{ 
var isValid = true; 
var username = document.getElementById("username").value; 
if (username==null||username==""){ 
    alert("WRong input"); 
    isValid = false; 
} 
if(isValid == true) 
{ 
    return true; 
} 
return false; 
} 
</script> 
</head> 
<body> 
<form action = "regServlet" method = "POST" onsubmit="return validate_form()"> 
<table id="regTable"> 
    <tr> 
    <td class="firstRow">Username:</td> 
    <td><input type="text" name="username" value="" size="15"/></td> 
    </tr> 
</table> 
<input style="margin:auto;" type="image" name="loginB" src="../img/login_button.png" /> 
</form> 
</body> 
</html> 

它是在Tomcat中6 运行当我跑步时的页面JSP文件,我的JavaScript函数不会在所有的工作。我在函数的开始处用alert来检查它。 我的问题是什么?我忘了什么? Eclipse在表单行上写入错误(其中出现onsubmit): 无法从函数或方法外部返回。

感谢

+0

这是代码,因为它的呈现? – Phil

回答

1

你需要id=username因为你有

document.getElementById("username") 
1

你需要给你的输入与name="username"也是一个id="username"

DEMO:http://jsfiddle.net/maniator/tf5zA/

而且你的JS可能会更清洁:

function validate_form() { 
    var isValid = true; 
    var username = document.getElementById("username").value; 
    if (username == null || username == "") { 
     alert("WRong input"); 
     isValid = false; 
    } 
    return isValid; 
} 
+0

谢谢你和一个非常好的演示网站。 – user893269