-2

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}`;
        
    };
});
ncl36
  • 1
  • 1
    Unless you `return false;` from the `onsubmit` function, the browser will take its normal action, which is to send the form data as a new GET request and refresh the page. – Tim Roberts Jan 26 '23 at 04:44

1 Answers1

-1

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}`;
        
    };
});
EDev
  • 400
  • 3
  • 10