0

Upon clicking submit, the function doesn't seem to get called and the form submits even if the return is 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:

    <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>
Ania Warzecha
  • 1,796
  • 13
  • 26

3 Answers3

1

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;
  }
bobthedeveloper
  • 3,733
  • 2
  • 15
  • 31
  • 1
    Instead of `return false`, you need to use `event.preventDefault()` to stop the form submission. – roshiro Apr 19 '14 at 19:03
0

When making a condition on an if statement the "is equal to" comparison symbol is == or ===. = is used for assigning variables.

Lugia101101
  • 685
  • 1
  • 7
  • 21
0

There's already an answer for that here -> onsubmit method doesn't stop submit

Basically you need to use event.preventDefault() to stop the form submission.

Community
  • 1
  • 1
roshiro
  • 770
  • 1
  • 5
  • 9