javascript onsubmit is not correctly working

46 Views Asked by At

All responses and help is greatly appreciated!

HTML:

<h1>CONTACT US</h1>
<form action="submit.html" target="_blank" method="post" onsubmit="return validate();">
  <label for="name">NAME</label>
  <input id="contact-name" name="name" placeholder="Please enter your name..." type="text">
  <label for="email">EMAIL</label>
  <input id="contact-email" name="email" placeholder="Please enter your contact email..." type="text">
  <label for="email">MESSAGE</label> 
  <textarea id="contact-message" name="message" placeholder="Please enter your message.."></textarea>
  <p></p>
  <input type="submit" id="submit" value="SUBMIT MESSAGE">
</form>

JAVASCRIPT:

function validate() {
    var username = document.getElementById("contact-name").value;
    var email = document.getElementById("contact-email").value;

    if (username==="" || email==="") {
        alert("Please can you fill in all fields");
        return false;
    } else {
        return true;
    }
};
1

There are 1 best solutions below

2
On

Are you sure you imported the file containing your Javascript into the HTML? See below:

function validate() {
    var username = document.getElementById("contact-name").value;
    var email = document.getElementById("contact-email").value;

    if (username==="" || email==="") {
        alert("Please can you fill in all fields");
        return false;
    } else {
        return true;
    }
}
<html>

<head>
</head>

<body>
  <h1>CONTACT US</h1>
  <form action="submit.html" target="_blank" method="post" onsubmit="return validate();">
    <label for="name">NAME</label>
    <input id="contact-name" name="name" placeholder="Please enter your name..." type="text">
    <label for="email">EMAIL</label>
    <input id="contact-email" name="email" placeholder="Please enter your contact email..." type="text">
    <label for="email">MESSAGE</label>
    <textarea id="contact-message" name="message" placeholder="Please enter your message.."></textarea>
    <p></p>
    <input type="submit" id="submit" value="SUBMIT MESSAGE">
  </form>
  <script src="script.js"></script>
</body>

</html>