0

I'm making a guessing game project and I have all the logic completed I am just having trouble with the output. The user enters their name and guess and submits and the program will check to see if the guess is correct,too high, too low and output their name + (Too high etc.) right below where you enter your guess. How I have mine set up, when you click the submit button it gets rid of all the text boxes and just outputs if you are right or wrong. I know I need to reinvoke the function to obtain this output, but I am rather new to JS and I'm not quite sure how to achieve this. Any tips and pointers are appreciated thank you all!

CODE:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Number Guess My Number Game!</title>

  <style>
    html {
      font-family: sans-serif;
    }

    body {
      width: 50%;
      max-width: 800px;
      min-width: 480px;
      margin: 0 auto;
    }
  </style>
</head>

<body>
  <h1>Guess My Number!</h1>

  <p>Valid Numbers are: 1 through 100</p>

  <div class="form">
    <label for="nameField">Enter your first NAME: </label>
    <input type="text" id="nameField" class="nameField"><br>
    <label for="submit"> Enter your Guess: </label>
    <input type="text" id="guessField" class="glassField">
    <input type="submit" value="Submit data" class="submit" id="submit">



  </div>

  <script type="text/javascript">
    var y = Math.floor(Math.random() * 100) + 1;


    document.getElementById("submit").onclick = function() {


        var x = document.getElementById("guessField").value;

        if (x == y) {
          document.write(nameField + "You are right! Enter a new number to try 
            again!"); 
          }
          else if (x > y) {
            document.write(nameField + "Your guess is too high");
          } else {
            document.write(nameField + "Your guess is too low");
          }
        }
  </script>
</body>

</html>
zfrisch
  • 7,744
  • 1
  • 18
  • 31
Josh Smith
  • 19
  • 1
  • 10
  • 2
    document.write is the WRONG thing to be using here. document.write replaces the page. – epascarello Oct 11 '18 at 14:45
  • https://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice – epascarello Oct 11 '18 at 14:48
  • The code you've provided seems to have a syntax error, but beyond that, `document.write` will trash everything in the DOM and replace it with your text. You're going to want to edit an element's text by using `textContent`, `innerHTML`, `insertAdjacentText`, or `insertAdjacentHTML`. – zfrisch Oct 11 '18 at 14:50

1 Answers1

0

Please take a look at this https://jsfiddle.net/n3ov4bt2/. It is kind of quick and dirty solution. I use innerText instead of document.write

resultElement.innerHTML = nameField.value + " You are right! Enter a new number to try again!"; 
Sergii Vorobei
  • 1,422
  • 8
  • 18