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>
4
  • 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. Commented Aug 17, 2022 at 19:14
  • querySelectr is a typo Commented Aug 17, 2022 at 19:15
  • stackoverflow.com/a/50803477/128761 Commented Aug 18, 2022 at 4:46
  • Does this answer your question? Prevent Default on Form Submit jQuery Commented Sep 7, 2022 at 0:39

1 Answer 1

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}!`);
    };
});
Sign up to request clarification or add additional context in comments.

3 Comments

It doesn't solved
There was also a typo in querySelector, but I've updated my answer. It should now work.
e.preventDefault() do not need, problem was with missed o is querySelector. Thank you for your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.