Can't get basic form to work

PreventDefault isn’t working. The alert doesn’t appear.

My code:

<!DOCTYPE html>
<html>
    <head>
      <style>
    * { 
	text-align: center;
	font-family: Arial;
	}
	
	#btn {
	margin-top: 20px;
	}
	
        </style>
    </head>

    <body>
        <h1>Tests</h1>
        <form>
           <div><input id="info" type="text" /></div>
           <div><button id="btn" type="submit">Enter</button></div>
        </form>

    <script>
    function respond(event) {
        event.preventDefault();
        alert("Hi there!");
		return false;
    }

    document.getElementById("btn").addEventListener("submit", respond);
    </script>
    </body>
    </html>

All I’m trying to do is stop the default refreshing and get the alert to show up. This is super basic, but it’s not working and I can’t figure out why not.

Try changing “submit” to “click”. You should be listening for a click event and then the preventDefault will stop the form from trying to reload the page.

Okay, click works, but I want to submit the form. I simplified the form for posting, but my actual form has required fields. Using a click event means they aren’t checked for being filled in.

The submit event should work. It works on other forms I have. I cannot see the difference.

It seems you you should be adding an event listener on the form element for “submit” and not an element named btn (which there is no such thing).

Okay, thank you, that does work. Thanks very much!

But the submit button is the element with the id “btn”, and that’s what is clicked to submit the form, so I’d still like to know (anyone?) why it works for the form’s id and not for the submit button’s id.

I need to correct something I said. I misread your code the first time I looked at it. You are correct in adding an event handler to the button with id=“btn”, but the event for which the button should be listening is the “click” event and not the “submit” event. The following will work.

document.getElementById("btn").addEventListener("click", respond);