2012-09-19 147 views
1

請使用我的表單尋求幫助。我想要使​​文本字段和複選框必填字段。該複選框正在驗證,我現在需要的只是文本字段要求驗證。我正在使用JavaScript。驗證文本字段和複選框

HTML:

<form name="form" method="post" action="result.php" onSubmit="return checkme()"> 
<table cellpadding="0" cellspacing="0" border="0"> 
<tr> 
<td>Name: </td> 
<td> <input name="Name" type="text" id="Name" size="20"></td> 
</tr> 
<tr> 
<td>Email: </td> 
<td> <input name="Email" type="text" id="Email" size="20"></td> 
</tr> 
<tr> 
<td colspan="2" align="center"><input type="checkbox" name="agree" value="agree_terms"> I agree to the terms</td> 
</tr> 
<tr> 
<td colspan="2" align="center"><input type="submit" name="submit" value="Submit">  <input type="reset" name="reset" value="Clear"></td> 
</tr> 
</table> 
</form> 

的Javascript:

<script language="JavaScript" type="text/JavaScript"> 
<!--//hide script 
function checkme() { 
missinginfo = ""; 
if (!document.form.agree.checked) { 
missinginfo += "\n - You must agree to the terms"; 
} 
if (missinginfo != "") { 
missinginfo ="__________________________________\n" + 
"Required information is missing: \n" + 
missinginfo + "\n__________________________________" + 
"\nPlease complete and resubmit."; 
alert(missinginfo); 
return false; 
} 
else { 
return true; 
} 
} 

</script> 

回答

0

添加這個JS代碼,用於驗證文本字段

if(document.form.Name.value==""){ 
missinginfo += "Required field"; 
} 

同爲電子郵件領域也。

+0

謝謝你的幫助! – Tam

0

如果你轉換到DOCTYPE <!DOCTYPE html>那麼你可以使用

required="true" 

將實現如下

<input name="Name" type="text" id="Name" size="20" required="true"> 

大多數瀏覽器支持HTML5。或者使用jQuery validation,使用起來相當簡單。

+0

謝謝你工作:) – Tam