Learning to pull data from a form with JS

I’m teaching myself Javascript and for my first attempt at applying some concepts I made a basic number guessing game. I can’t seem to get it to work though! Would someone mind taking a look and helping me figure out where I’ve gone wrong? It’s very VERY basic and I’m sure there’s some simple concept I haven’t learned or have overlooked.

I’m trying to get the user to guess the number 6!

var myNum = 6;
var userGuess = document.getElementById("number").value;
if (userGuess == myNum) {
            writeMessage('statusArea', '<p>"You guessed my favorite number!"</p>');}
  if (userGuess > myNum) {
            writeMessage('statusArea', '<p>"Nope, too high, try again!"</p>');}
if (userGuess < myNum) {
            writeMessage('statusArea', '<p>"Nope, too low, try again!"</p>');}
<header>Can you guess my favorite number?</header>
<body>
  <form><label for="number">Enter a number here:</label><br>
    <input type="text" id="number" name="number"><br><input type="submit" value="Guess"></form> 
  
  <div id="statusArea"></div>
</body>

https://codepen.io/The_vagabond_blonde/pen/KKNgOrm

1 thought on “Learning to pull data from a form with JS”

  1. There were multiple problems. But when using a submit button the form is submitted instead of the JS code. Thus you’re not seeing the text defined in JS. Below is how to prevent that from happening. Also since you’re working with numbers you need to make the value a number as by default it would be string. Then it is also recommended to use === over == as explained here

    var myNum = 6;
    
    document.getElementById('guessNumber').addEventListener('click', function(e) {
      e.prevenDefault; // Prevents submitting form
      var userGuess = Number(document.getElementById("number").value); // parse value to an actual number instead
      if (userGuess === myNum) { // use of === is recommended over == 
        writeMessage('statusArea', '<p>You guessed my favorite number!</p>');
      }
    
    
      // as userGuess is now a number you can check if it is more or less than
      if (userGuess > myNum) {
        writeMessage('statusArea', '<p>Nope, too high, try again!</p>');
      }
      
      if (userGuess < myNum) {
        writeMessage('statusArea', '<p>Nope, too low, try again!</p>');
      }
    });
    
    function writeMessage(domId, html)
    {
      document.getElementById(domId).innerHTML = html
    }
    <header>Can you guess my favorite number?</header>
    <body>
      <form>
        <label for="number">Enter a number here:</label><br>
        <input type="text" id="number" name="number"><br>
        <input type="button" id="guessNumber" value="Guess">
      </form> 
      
      <div id="statusArea"></div>
    </body>
    Reply

Leave a Comment