未经验证时提交的JavaScript表单

时间:2014-06-23 13:50:29

标签: javascript

我在提交时使用以下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'为空并且我点击提交时,我会在浏览器中看到警告弹出窗口,但是当我单击确定时,表单仍然会提交。

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

谢谢

2 个答案:

答案 0 :(得分:3)

您的脚本中有一个复制和粘贴错误: 请参阅表单名称: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;
}

答案 1 :(得分:1)

它失败了,因为当它实际命名为myForm时,你引用一个名为square.的表单如果你在运行代码时查看错误控制台,你会看到你得到{{1}因为这个。

将第Uncaught TypeError: Cannot read property 'PosX' of undefined行更改为document.myForm.PosX.focus() ;

<强> jsFiddle example

相关问题