Number Guessing Game... will not allow me to use <form>?

So I’ve actually completed the module, but had to come back to this. I had put my code side-by-side with your example code (from the live version) which works… as well as the other version I have where we corrected the errors (it, too, works just fine).

But my code from where we built it in the “A first splash into JavaScript” did not work. When I entered the initial number, it flashed for one second, then disappeared. It did this in my IDE and when I ran it through the browser.

The only difference in mine was that when I built mine, I used <form></form> instead of <div class="form"></div>. When I changed it back to <div>, it worked fine. The items inside were identical.

Why would using <form> cause an error? The class “form” is never called.

@mbrasseau ah yes, this is an interesting one. When I originally wrote this, I deliberately used a <div> instead of a <form> because it meant I could avoid having to explain a couple of things that I thought would confuse people at that point.

Maybe I should have used <form> — it is certainly better semantics.

Basically, when you have a button inside a form on a page, and you click it, the default behavior is that the form will be submitted. That means the browser tries to send the data the form contains to the server, and then sends you back to a destination page.

We haven’t specified a place on the server to send the data, or a destination page to go to after the form has submitted, so the browser basically just refreshes the current page. This is why your number flashes for a second then disappears.

You can stop the form from submitting using a method called preventDefault(), which is called on the event object of the event that fires when the form submits — this can be a click event on the button, or a submit event on the form itself.

In our case, we already have this in the code:

guessSubmit.addEventListener('click', checkGuess);

You click the button, it checks whether the guess is correct. To make this work when you are using a <form>, we could update it to this:

guessSubmit.addEventListener('click', function(e) {
  e.preventDefault();
  checkGuess();
});

So we’ve added an anonymous function inside the addEventListener call, in which we specify an e parameter to represent the event object. Then inside the function we call e.preventDefault() to stop the form from submitting, and then call the checkGuess() function.

That’s quite a lot of new concepts to introduce, which is why I think I avoided it in the first place.

1 Like