Issue
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>
Solution
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}!`);
};
});
If this solved your problem, you can mark it as correct.
Answered By - Michael M.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.