skip to Main Content

Why is this simple HTML and Javascript not working?

I just need to alert once the form is submitted. It instead is refreshing and throwing an error and sometimes throwing a CORS error also, if use type as module.

HTML File

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Home</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <link rel="stylesheet" href="styles.css" />
    <script type="JavaScript" src="script.js"></script>
  </head>
  <body>
    <form onsubmit="addUser(); return false">
      <label for="fname">First name:</label><br />
      <input type="text" id="fname" name="fname" value="" required /><br />
      <label for="lname">Last name:</label><br />
      <input type="text" id="lname" name="lname" value="" required /><br />
      <label for="lname">Phone number:</label><br />
      <input type="number" id="phone" name="phone" value="" required /><br /><br />
      <input type="submit" value="Submit" />
    </form>
  </body>
</html>

JavaScript File

function addUser() {
  console.log('Hello');
  alert('Hello');
}

2

Answers


  1. **In Html Form**
    < form onsubmit="addUser(event)">
    
    **And JavaScript**
    function addUser(e) {
      e.preventDefault()
      console.log('Hello');
      alert('Hello');
    }
    
    Login or Signup to reply.
  2. The problem here is that you are using type="JavaScript" on your <script> tag. Because "JavaScript" is not a valid JavaScript MIME-type, the block will be treated as a data block and wont be processed by the browser.

    This means that your addUser() function is never loaded in. Calling it will cause an error meaning that return false is never reached and thus the form submission will not be prevented.

    To fix it, either use the valid JavaScript MIME-type text/javascript. Or even better, omit the type attribute altogether.

    <script src="script.js"></script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search