I am new to JavaScript. I am trying to change my h1 tag value in HTML to a value based on form submitted. However, it displays only for a split second before disappearing. I would like to display the value permanently. Your advice is appreciated. Thank you.
The greeting was displayed only for a split second. I would like it to be displayed permanently. I suspect the issue is in the triggering of the event listener in JS code.
>! HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<title>Count</title>
<script src="counter.js"></script>
</head>
<body>
<h1>Cold</h1>
<form>
<input autofocus id="name" placeholder="Name" type="text">
<input type="submit">
</form>
</body>
</html>
>! JS code
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('form').onsubmit = function() {
const name = document.querySelector('#name').value;
document.querySelector('h1').innerHTML = `Hello ${name}`;
};
});
You have to add the preventDefault property to the event, so it does not refresh the page onSubmit:
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('form').onsubmit = function(event) {
const name = document.querySelector('#name').value;
event.preventDefault();
document.querySelector('h1').innerHTML = `Hello ${name}`;
};
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.