0

I have the following code and the e.preventDefault() doesn´t work. Always recharges the page. Could it be something on my computer?

html:

<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> </title>
  </head>

  <body>
    <script>src="app.js"</script>

    <form id="tweetForm">
      <input type="text" name="username" placeholder="username">
      <input type="text" name="tweet" placeholder="tweet">
      <button>Post</button>
    </form>

    
  </body>

</html>

Javascript:


const tweetForm = document.querySelector("#tweetForm")
tweetForm.addEventListener('submit', function (e) {
    console.log("SUBMIT!!")
    e.preventDefault();
});
SCoder20
  • 55
  • 1
  • 6
  • 1
    Move your script (after correcting the link) to before `

    `

    – j08691 Feb 10 '22 at 19:25
  • 2
    `` doesn’t do anything. Even if you use the correct ``, please see [Why does jQuery or a DOM method such as getElementById not find the element?](/q/14028959/4642212). Use `type="module"` or `defer`. – Sebastian Simon Feb 10 '22 at 19:26
  • Now the html script is like this, but still get an error: `
    `
    – SCoder20 Feb 10 '22 at 19:34
  • This is the error: index.html?username=&tweet=:19 Uncaught ReferenceError: src is not defined at index.html?username=&tweet=:19:30 – SCoder20 Feb 10 '22 at 19:35
  • @SCoder20 No… `src="app.js"` is an _attribute_. That was the point of my comment: _“Even if you use the correct `` […]”_. `` is invalid. It’s ``. It’s basic HTML syntax… – Sebastian Simon Feb 10 '22 at 19:36
  • Now it works. Thanks, I´m kind of new to html and js. – SCoder20 Feb 10 '22 at 19:41

1 Answers1

1

const tweetForm = document.querySelector("#tweetForm")

tweetForm.addEventListener('submit', function (e) {
    console.log("SUBMIT!!")
    e.preventDefault();
});
<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> </title>
  </head>
  <body>
    <!-- MOVE YOUR SCRIPT TO BOTTOM, JUST BEFORE CLOSE BODY TAG -->
    <!-- <script src="app.js"></script> -->
    <form id="tweetForm">
      <input type="text" name="username" placeholder="username">
      <input type="text" name="tweet" placeholder="tweet">
      <button>Post</button>
    </form>
    <!-- HERE IS GOOD, WITHOUT COMMENT NOTATION -->
    <!-- <script src="app.js"></script> -->
  </body>
</html>