簡體   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