簡體   English   中英

Safari表單提交-返回false無效

[英]Safari form submission - return false not working

這是我對Stack的第一篇文章-我是編碼的新手...

我在Safari中進行表單驗證時返回false時遇到問題。 return false在Chrome和Firefox上可以正常工作,但是當在Safari中提交不完整的表單時,會觸發警報,但無論如何仍會繼續提交表單。 這是相關的代碼,非常基本的東西...

if (dateField == null || dateField == "" || timeField == null || timeField == ""){

        if (dateField == null || dateField == ""){
            alert("Please select a date");
            }

        if (timeField == null || timeField == ""){
            alert("Please select a time");
            }

            return false;
        };

我也看到過類似的問題,但是沒有什么能解決我的問題。 無論如何,我知道這可能是一個非常業余的問題,但是非常感謝您的幫助。 謝謝!

我假設您將一個函數綁定到按鈕(或其他按鈕)上的click事件,然后驗證表單。

不同的瀏覽器對此有不同的實現。 例如,某些瀏覽器將獲取綁定到元素的函數的返回值(在這種情況下,返回false足以停止按鈕的默認行為)。 其他人沒有。

為了確保它能按預期方式工作,您必須使用preventDefault函數。

在此示例中,該函數是您綁定到元素的click事件的函數。 但是,您必須將事件傳遞給它(在本例中為e

function(e) {
  e.preventDefault();

  // Your code
  if (dateField == null || dateField == "" || timeField == null || timeField == ""){

    if (dateField == null || dateField == ""){
      alert("Please select a date");
    }

    if (timeField == null || timeField == ""){
      alert("Please select a time");
    }

    // Just like you did correctly, return false
    return false;
  }
}

根據您的需要,您必須將preventDefault()向下移至return false;之上return false; (如果您希望在驗證成功后執行正常的操作,那么我假設您要這樣做)。

要阻止發送表單,只需使用Event.preventDefault

我不確定您的HTML到底是什么樣,但是我確定您可以使用document.getElementById修改行,並確保您的表單具有methodaction屬性並且沒有內聯事件處理程序(即onsubmit="…" )。

// Assuming the DOM is loaded at this point.

var yourForm=document.getElementById('yourForm');

yourForm.addEventListener('submit',function(e){
  "use strict";
  /* If you want to use variables,
     make sure to update their value before checking. */
  var dateField=document.getElementById('dateField').value,
    timeField=document.getElementById('timeField').value;

  if(!dateField || !timeField){ // Validation
    // Message
    if(!dateField){
      alert("Please select a date.");
    }
    else if(!timeField){
      alert("Please select a time.");
    }

    // Prevent the form from sending
    if(e.preventDefault){
      e.preventDefault();
    }
    else if(e.returnValue){
      e.returnValue=false; // For IE8
    }
    return false; // Just to be safe
  }
});
<!-- Here’s a potential HTML structure: -->
<form id="yourForm" action="somewhere.php" method="GET">
  <input id="dateField" type="text"/>
  <input id="timeField" type="text"/>
  <input type="submit"/>
</form>

如此SO問題所指出的那樣,設置e.returnValue只是與Internet Explorer 8兼容的一種方式。 如果要與這些舊版瀏覽器完全兼容,則還需要兼容版本的addEventListener 您可以使用jQuery。 而且您不需要刪除return false; ,或者。

另外,在驗證輸入時請小心。 與空字符串進行比較時,請使用===!==避免鍵入強制。 如果確定輸入元素始終存在,那么簡單的!field.value就足夠了。 我建議使用JSHint驗證您的代碼。

上面的代碼應涵蓋在大多數現代瀏覽器中取消提交。 如果仍然有問題,可以采取一種解決方法,並禁用提交按鈕或刪除method屬性,或者如果字段無效,則應刪除類似的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM