'e.preventDefault() not working always reloads
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();
});
Solution 1:[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>
Solution 2:[2]
Solution ?
First of all correct <script>src="app.js"</script>. The src attribute should be inside the tag. Then try one of these solutions:
Place the script tag after all elements in the body.
Or, add
deferattribute to the script tag:<script src="/app.js" defer></script>.Or, place your code inside
DOMContentLoadedevent callback:
document.addEventListener('DOMContentLoaded', () => {
const tweetForm = document.querySelector('#tweetForm')
tweetForm.addEventListener('submit', e => {
console.log('SUBMIT!!')
e.preventDefault()
})
}, false)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Deiby Rodriguez |
| Solution 2 | sultan |
