0

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>
  • Your form without `method` will be submit using `GET` by default. Your JS event handler did not prevent default action for the form submit, that's why when you click button and it's just like reload. – vee Aug 17 '22 at 19:14
  • `querySelectr` is a typo – IT goldman Aug 17 '22 at 19:15
  • https://stackoverflow.com/a/50803477/128761 – vee Aug 18 '22 at 04:46
  • Does this answer your question? [Prevent Default on Form Submit jQuery](https://stackoverflow.com/questions/6462143/prevent-default-on-form-submit-jquery) – Heretic Monkey Sep 07 '22 at 00:39

1 Answers1

1

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}!`);
    };
});
Ryan M
  • 18,333
  • 31
  • 67
  • 74
Michael M.
  • 10,486
  • 9
  • 18
  • 34