Safari 表单提交 - return false 无效

Safari form submission - return false not working

这是我第一次 post 堆栈 - 我对编码还很陌生...

我在 Safari 中遇到表单验证 return 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;
        };

我见过类似的问题,但没有什么能完全解决我的问题。无论如何,我知道这可能是一个非常业余的问题,但我非常感谢你的帮助。谢谢!

我假设您正在将一个函数绑定到按钮(或其他东西)上的点击事件,然后验证您的表单。

不同的浏览器对此有不同的实现。例如,某些浏览器将采用绑定到元素的函数的 return 值(在这种情况下,return false 足以停止按钮的默认行为)。其他人没有。

为确保它按照您的预期运行,您必须使用 preventDefault 功能。

在这个例子中,函数就是你绑定到元素点击事件的函数。你必须将事件传递给它(在这种情况下称为 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; 的正上方(如果您愿意,我假设在您的情况下您会想要这样做如果您的验证成功,将发生的正常操作)。

要阻止发送表单,只需使用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>

设置e.returnValue只是一种兼容Internet Explorer 8的方法,正如this SO question. If you want to be fully compatible to these older browsers, you’ll need a compatible version of addEventListener as well. You can use jQuery for that. And you don’t need to remove return false;中指出的那样。

此外,请在验证您的输入时小心。与空字符串进行比较时,请使用 ===!== 以避免类型强制转换。如果您确定输入元素始终存在,那么简单的 !field.value 就足够了。我建议使用 JSHint.

验证您的代码

以上代码应该涵盖在大多数或多或少的现代浏览器中取消提交。如果仍然有问题,您可以采取解决方法并禁用提交按钮或删除 method 属性或类似字段(如果字段无效)。