繁体   English   中英

未验证时提交JavaScript表单

[英]JavaScript form submitting when not validating

提交时,我使用以下JS验证表单:-

function validate()
{
   if( document.square.PosX.value == "" )
   {
     alert( "Please pick where in the square you think we are" );
     document.myForm.PosX.focus() ;
     return false;
   }
   return true;
}

<form name="square" action="save_results.php" method="post" onsubmit="return validate();">
         <input type="text" id="PosX" name="PosX">
         <input type="submit" value="Submit">
</form>

当“ PosX”字段为空并且单击“提交”时,我会在浏览器中看到警报弹出窗口,但是当我单击“确定”时,表单仍会提交。

除非表单字段不为空,如何防止它实际提交?

谢谢

您的脚本中存在复制和粘贴错误:请参见表单名称: document.square.PosX.focus() ;

function validate()
{
   if( document.square.PosX.value == "" )
   {
     alert( "Please pick where in the square you think we are" );
     document.square.PosX.focus() ;
     return false;
   }
   return true;
}

之所以失败,是因为您实际上是在引用名为myFormsquare.的表单square. 如果在运行代码时查看错误控制台,则会看到Uncaught TypeError: Cannot read property 'PosX' of undefined

更改行document.myForm.PosX.focus() ; document.square.PosX.focus();

jsFiddle示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM