Reputation: 3
In all the codes that I wrote, the button does not work. The site simply reloads and that's it. Maybe this is an error not in the code, but in something else, please help This is my code
<!DOCTYPE html>
<html lang="'en">
<head>
<title>Hello</title>
<script>
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('form').onsubmit = function() {
const name = document.querySelectr('#name').value;
alert(`Hello, ${name}!`);
};
});
</script>
</head>
<body>
<h1>Hello!</h1>
<form>
<input autofocus id="name" placeholder="Name" type="text">
<input type="submit">
</form>
</body>
</html>
Upvotes: 0
Views: 45
Reputation: 11090
By default, a submit button will reload the page to send a request. This can be prevented with e.preventDefault()
. Here's an example with your code:
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('form').onsubmit = function(e) {
e.preventDefault();
const name = document.querySelector('#name').value;
alert(`Hello, ${name}!`);
};
});
Upvotes: 1