简体   繁体   English

提交不调用JavaScript函数

[英]Submit not calling JavaScript function

Upon clicking submit, the function doesn't seem to get called and the form submits even if the return is false. 单击提交后,该函数似乎没有被调用,即使返回为false,该表单也将提交。

    function validateForm() {
        if (document.getElementById("nm").value="")  {
            alert("You must enter a name!"); 
            return false;
        }
        if (document.getElementById("em").value="")  {
            alert("email required"); 
            return false;
        }
    return true;
    }

And the HTML: 和HTML:

    <form onsubmit=" return validateForm();" action="myscript.php" id="primary">
        <label>Name<input type="text" id="nm"></input></label>
        <label>Email<input type="text" id="em"></input></label>
        <input type="submit" id="send" value="submit"></input>
    </form>

You should use the == or === (exact equal to) to compare values, the = operator is used to assign values. 您应该使用===== (精确等于)比较值, =运算符用于分配值。

 function validateForm() {
    if (document.getElementById("nm").value == "")  {
        alert("You must enter a name!"); 
        return false; 
    }

    if (document.getElementById("em").value == "")  {
        alert("email required"); 
        return false; 
    }

    return true;
  }

When making a condition on an if statement the "is equal to" comparison symbol is == or === . if语句中设置条件时,“等于”比较符号为===== = is used for assigning variables. =用于分配变量。

There's already an answer for that here -> onsubmit method doesn't stop submit 这里已经有了答案-> onsubmit方法不会停止提交

Basically you need to use event.preventDefault() to stop the form submission. 基本上,您需要使用event.preventDefault()来停止表单提交。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM