我有一个带JS函数的表单来验证没有空白字段,
但它不起作用。
<head>
<script language='javascript'>
function verifyForm(){
var msg='';
if(document.getElementById('field1').value==''){msg+='Field 1 \n';}
if(document.getElementById('field2').value==''){msg+='Field 2 \n';}
if(msg!=''){
alert('The following entries are empty:\n\n'+msg);
return false
}else{
return true }
}
</script>
</head>
<body>
<form name="frmRequest2" id="frmRequest2" action="<? echo $submitURL2; ?>" method="post" onsubmit='return verifyForm();'>
Please answer all questions and enter "NONE" where appropriate.
<table>
<tbody>
<tr>
<th>List any items you already have</th>
<th>List any items you need to get</th>
</tr>
<tr>
<td><textarea name="field1" id="field1" rows="2" cols="39"> <? echo $field1; ?> </textarea></td>
<td><textarea name="field2" id="field2" rows="2" cols="39"> <? echo $field2; ?> </textarea></td>
</tr>
<tr>
<td colspan="4" align="center" valign="top" style="border-width: 0px 0px 0px 0px;"> <br />
<input name="submit" value="Submit Data" type="submit"/> </td>
</tr>
</tbody>
</table>
</form>
</body>
答案 0 :(得分:4)
你的if子句后面有额外的大括号(}
)。
编辑添加:以下代码按预期工作,并忽略字段中的任何前导/尾随空格:
<html>
<head>
<script language='javascript'>
function verifyForm(){
var msg='';
if(document.getElementById('field1').value.replace(/\s+$|^\s+/, '') == '') {msg+='Field 1 \n';}
if(document.getElementById('field2').value.replace(/\s+$|^\s+/, '') == '') {msg+='Field 2 \n';}
if(msg!=''){
alert('The following entries are empty:\n\n'+msg);
return false;
}else{
return true;
}
}
</script>
</head>
<body>
<form name="frmRequest2" id="frmRequest2" action="" method="post" onsubmit='return verifyForm();'>
Please answer all questions and enter "NONE" where appropriate.
<table>
<tbody>
<tr>
<th>List any items you already have</th>
<th>List any items you need to get</th>
</tr>
<tr>
<td><textarea name="field1" id="field1" rows="2" cols="39"></textarea></td>
<td><textarea name="field2" id="field2" rows="2" cols="39"></textarea></td>
</tr>
<tr>
<td colspan="4" align="center" valign="top" style="border-width: 0px 0px 0px 0px;">
<input name="submit" value="Submit Data" type="submit"/>
</td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
答案 1 :(得分:1)
你错过了一个“&gt;”在你的关闭“[/ head]”标签上,你没有关闭你的“[form]”标签。这可能会导致问题。
答案 2 :(得分:1)
每个默认值的每一侧都有一个空格。 "" != " "
答案 3 :(得分:0)
作为一般规则,我喜欢修剪输入空间。是否将if子句更改为
document.getElementById('field1').value == '' to
document.getElementById('field1').value.trim() == ''
有帮助吗?
另外,为了重申大卫建议的内容,您的原始代码看起来像
<textarea name="field1" id="field1" rows="2" cols="39"><? echo $field1; ?></textarea>
而不是
<textarea name="field1" id="field1" rows="2" cols="39"> <? echo $field1; ?> </textarea>
注意空格?