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

时间:2022-11-23 19:44:14

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 Login servlet also called automatically, which is a wrong thing..Why this happens? Any solution?

问题是javaScript在我正确设置时发出警报,但最后Login servlet也自动调用,这是一个错误的事情。为什么会发生这种情况?有解决方案吗

6 个解决方案

#1


4  

Redirect to Login happens because you have js error.

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

You dont define variable id and psw.

你没有定义变量id和psw。

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;

#2


2  

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>

#3


1  

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这样的东西重新编写这个函数,你会发现模型更直观,跨平台友好。

#4


1  

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,我们可以检查一下。

#5


1  

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>

#6


0  

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

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

onsubmit="return false;"

Not sure what was going on... in any case moving the event trigger to the submit button's onclick event fixed the problem.

不知道发生了什么......无论如何将事件触发器移动到提交按钮的onclick事件修复了问题。

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

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

#1


4  

Redirect to Login happens because you have js error.

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

You dont define variable id and psw.

你没有定义变量id和psw。

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;

#2


2  

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>

#3


1  

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这样的东西重新编写这个函数,你会发现模型更直观,跨平台友好。

#4


1  

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,我们可以检查一下。

#5


1  

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>

#6


0  

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

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

onsubmit="return false;"

Not sure what was going on... in any case moving the event trigger to the submit button's onclick event fixed the problem.

不知道发生了什么......无论如何将事件触发器移动到提交按钮的onclick事件修复了问题。

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

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