提交不调用JavaScript函数

时间:2014-04-19 17:06:40

标签: javascript forms validation submit onsubmit

单击“提交”后,即使返回值为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;
    }

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>

3 个答案:

答案 0 :(得分:1)

您应该使用=====(完全相等)来比较值,=运算符用于指定值。

 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;
  }

答案 1 :(得分:0)

if语句中创建条件时,“等于”比较符号为======用于分配变量。

答案 2 :(得分:0)

这里已经有了答案 - &gt; onsubmit method doesn't stop submit

基本上您需要使用event.preventDefault()来停止表单提交。