Javascript 为什么当我从 onsubmit 返回 false 时我的 HTML 表单仍然提交?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7723381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:20:58  来源:igfitidea点击:

Why does my HTML form still submit when I return false from onsubmit?

javascripthtmlforms

提问by Asif

I wrote a simple script for validating login form as follows:

我写了一个简单的脚本来验证登录表单,如下所示:

<script type="text/javascript">
    function validateLoginForm(){
    var idV = document.forms["LoginForm"]["id"].value;
    var pwdV = document.forms["LoginForm"]["pwd"].value;

    if (idV == null || idV == "" || idV.length < 5) {
          alert("user ID must be filled and of more than 4 characters!!");
          id.focus();
          return false;
    }

    if (pwdV == null || pwdV == "" || pwdV.length < 5) {
        alert("Password must be filled and of more than 4 characters!!");
        pwd.focus();
        return false;
    }

    return true;
}
</script>

and call it as :

并将其称为:

<form name="LoginForm" method="POST" onsubmit="return validateLoginForm()" action="Login" >
.
.
.
.
</form>

The problem is that javaScript gives out the alert as i set correctly but in the end the Loginservlet also called automatically, which is a wrong thing..Why this happens? Any solution?

问题是 javaScript 在我正确设置时发出警报,但最后Loginservlet 也自动调用,这是错误的事情..为什么会发生这种情况?有什么解决办法吗?

采纳答案by Vasily

Redirect to Login happens because you have js error.

重定向到登录是因为您有 js 错误。

You dont define variable idand psw.

您没有定义变量idpsw.

So when you try id.focus()or psw.focus()- you have js error and return true by default

所以当你尝试id.focus()psw.focus()- 你有js错误并默认返回true

So add this code:

所以添加这个代码:

var id = document.forms["LoginForm"]["id"];
var pwd = document.forms["LoginForm"]["pwd"];
var idV = document.forms["LoginForm"]["id"].value;
var pwdV = document.forms["LoginForm"]["pwd"].value;

回答by mymotherland

Try this,

尝试这个,

<script type="text/javascript">
    function validateLoginForm(){
    var idV = document.forms["LoginForm"]["id"].value;
    var pwdV = document.forms["LoginForm"]["pwd"].value;
    var err = '';
    if (idV == null || idV == "" || idV.length < 5) {
          err = "user ID must be filled and of more than 4 characters!! \n";
          document.getElementById("id").focus()
    }

    if (pwdV == null || pwdV == "" || pwdV.length < 5) {
        err  = "Password must be filled and of more than 4 characters!! \n";
         document.getElementById("pwd").focus()
    }
    if(err == '')
        return true;
    else
      {
        alert(err);
        return false;
      }
}
</script>

回答by shawty

Without you putting in the entire contents of your form I cannot be sure, but I'm going to take a good guess here. I'm going to say that your tags for your user ID and password fields ONLY have name attributes on them?

如果没有您输入表单的全部内容,我无法确定,但我将在这里进行一个很好的猜测。我要说的是,您的用户 ID 和密码字段的标签仅具有名称属性?

When your dealing with forms in HTML, you have to use 'name=' for the parameter names to be passed onto the receiving script. This is what gives your script the ?id=blah&pwd=blah bit in the URL or as the post data payload.

当您处理 HTML 中的表单时,您必须使用 'name=' 作为要传递到接收脚本的参数名称。这就是为您的脚本提供 URL 中的 ?id=blah&pwd=blah 位或作为发布数据有效负载的原因。

However....

然而....

When your accessing values using the DOM (Document object model) as you are in your script, then you need to have the element identified with an 'id=' attribute.

当您在脚本中使用 DOM(文档对象模型)访问值时,您需要使用 'id=' 属性标识元素。

The same holds true for any element anywhere in your doc that you need to access using a scripted approach in js.

对于您需要使用 js 中的脚本化方法访问的文档中任何位置的任何元素也是如此。

If you notice also, you get the alert, but as-well as not returning false, your focus call also never gets called, it will be this that's causing your script to abort as an element called 'id' cannot be found.

如果您也注意到了,您会收到警报,但除了不返回 false 之外,您的焦点调用也永远不会被调用,这将导致您的脚本中止,因为找不到名为“id”的元素。

add id="id" and id="pwd" next to your name="id" and name="pwd" attributes in your input tags, and you should find that all will work as expected. EG:

在输入标签中的 name="id" 和 name="pwd" 属性旁边添加 id="id" 和 id="pwd",您应该会发现所有内容都会按预期工作。例如:

    <input type="text" name="id" id="id" ... />

On a last note, I would encourage you however, to re-write this function using something like jQuery, you'll find the model much more intuitive and cross platform friendly.

最后,我鼓励您使用 jQuery 之类的东西重新编写此函数,您会发现该模型更加直观且跨平台友好。

回答by Paul D. Waite

I've created a minimal test case here: http://www.pauldwaite.co.uk/test-pages/7723381/

我在这里创建了一个最小的测试用例:http: //www.pauldwaite.co.uk/test-pages/7723381/

<script>
function pretendValidation(){
    alert("Validatation failed!");
    return false;
}
</script>

<form action="http://www.google.co.uk/" method="POST" onsubmit="return pretendValidation();">
    <input type="submit" value="Submit">
</form>

When I click on “Submit”, the alert happens, and the form does not submit. So in theory, your code should work.

当我点击“提交”时,警报发生,并且表单没有提交。所以理论上,你的代码应该可以工作。

As @Shawty mentioned, you may have a problem with your form HTML. If you post all the HTML as well, we can check that.

正如@Shawty 提到的,您的表单 HTML 可能有问题。如果您也发布了所有 HTML,我们可以检查一下。

回答by Black

Best practice: if you want to guarantee not to submit the form, even if your Javascript throws en exception, you should wrap your code in try/catch blocks:

最佳实践:如果您想保证不提交表单,即使您的 Javascript 抛出异常,您也应该将代码包装在 try/catch 块中:

<script type="text/javascript">


function validateLoginForm(){
  try{
    var idV = document.forms["LoginForm"]["id"].value;
    var pwdV = document.forms["LoginForm"]["pwd"].value;

    if (idV == null || idV == "" || idV.length < 5) {
      alert("user ID must be filled and of more than 4 characters!!");
      id.focus();
      return false;
    }

    if (pwdV == null || pwdV == "" || pwdV.length < 5) {
      alert("Password must be filled and of more than 4 characters!!");
      pwd.focus();
      return false;
    }
 }catch(e){
   console.log(e);
   return false;
 }

return true;
}
</script>

回答by Serj Sagan

Well, strangely enough my form was still submitted even when I returned falsefrom my functionand returned that function's return to the form's onsubmit... I even tried:

好吧,奇怪的是,即使我false从我function的返回并返回该函数的返回到表单的返回,我的表单仍然被提交onsubmit......我什至尝试过:

onsubmit="return false;"

Not sure what was going on... in any case moving the event trigger to the submitbutton's onclickevent fixed the problem.

不确定发生了什么......无论如何,将事件触发器移动到submit按钮的onclick事件可以解决问题。

Update: Ended up finding that the code I was editing had another JS handler attached to the onsubmitevent which is why it was ignoring my return false;

更新:最终发现我正在编辑的代码有另一个 JS 处理程序附加到onsubmit事件,这就是为什么它忽略了我的return false;