Home > other >  How to save multiple user inputs into new variables
How to save multiple user inputs into new variables

Time:09-10

Im creating a guessing game and the user has 5 attempts to make the correct guess. I want to save their previous guesses (inputs) to show it to them. I have been using the snippet below to save one attempt when the user types into an <input> field, but how can I save the next 4 attempts in new variables such as userGuess2, userGuess3, etc.

var userGuess = document.getElementById("inputField").value;
$('#previousGuesses').text(userGuess);

CodePudding user response:

Ok then let's pretend this is your input

<input type="text" id="inputField">

You can create an index that will increment everytime the users presses enter to save another answer

var i=1;

And the id name your autogenerated spans will have

var name = "previousGuesses";

Now on your function you will save the value when the user presses enter like you described and when that happens it will create a new span element where it will display the value stored

 function myFunction(){
    $("#inputField").keypress(function( event ) {
        if ( event.which == 13  || event.which == 9) {
            var userGuess = document.getElementById("inputField").value;//get value of the answer
            var span = document.createElement('SPAN');//create a new span
            span.innerHTML = userGuess   "<br>";//answer value goes here
            span.id = name i;//this is the id of your new span, remember ids are unique so we attach var i to the name var we declared before
            document.body.appendChild(span);
            //$('#previousGuesses' i).text(userGuess);
        i  ;
        }
    });
}

now call your function

myFunction();

https://jsfiddle.net/kenpy/m16bojhg/4/

CodePudding user response:

You can just simply add an element for the user's last attempts and add to it.

f(guessCount === 1) {
  guesses.textContent = 'Previous guesses: ';
}
guesses.textContent  = userGuess   ' ';

 var randomNumber = Math.floor(Math.random() * 100)   1;
      var guesses = document.querySelector('.guesses');
      var lastResult = document.querySelector('.lastResult');
      var lowOrHi = document.querySelector('.lowOrHi');
      var guessSubmit = document.querySelector('.guessSubmit');
      var guessField = document.querySelector('.guessField');
      var guessCount = 1;
      var resetButton;
      guessField.focus();
      function checkGuess() {
        var userGuess = Number(guessField.value);
        if(guessCount === 1) {
          guesses.textContent = 'Previous guesses: ';
        }
        guesses.textContent  = userGuess   ' ';
        if(userGuess === randomNumber) {
          lastResult.textContent = "Good job! You win!";
          lastResult.style.backgroundColor = 'green';
          lowOrHi.textContent = '';
          setGameOver();
        } else if(guessCount === 10) {
          lastResult.textContent = 'Hahaha You suck!';
          lowOrHi.textContent = '';
          setGameOver();
        } else {
          lastResult.textContent = "Oops! You're Wrong!";
          lastResult.style.backgroundColor = 'red';
          if(userGuess < randomNumber) {
            lowOrHi.textContent = 'Last guess was too low!';
          } else if(userGuess > randomNumber) {
            lowOrHi.textContent = 'Last guess was too high!';
          }
        }
        guessCount  ;
        guessField.value = '';
        guessField.focus();
      }
      guessSubmit.addEventListener('click', checkGuess);
      console.log('cheat is: '   randomNumber);
      function setGameOver() {
        guessField.disabled = true;
        guessSubmit.disabled = true;
        resetButton = document.createElement('button');
        resetButton.textContent = 'Play Again?';
        document.body.appendChild(resetButton);
        resetButton.addEventListener('click', resetGame);
      }
      function resetGame() {
        guessCount = 1;
        var resetParas = document.querySelectorAll('.resultParas p');
        for(var i = 0 ; i < resetParas.length ; i  ) {
          resetParas[i].textContent = '';
        }
        resetButton.parentNode.removeChild(resetButton);
        guessField.disabled = false;
        guessSubmit.disabled = false;
        guessField.value = '';
        guessField.focus();
        lastResult.style.backgroundColor = 'white';
        randomNumber = Math.floor(Math.random() * 100)   1;
      }
body{
  background-image: linear-gradient(to left top, #c6fced, #a3efda, #7fe3c7, #54d5b3, #00c89f);
  color: #2F3139;
  margin: 10rem auto;
  height:50vh;
}
h1 {
  font-size: 1.5rem;
}

.lastResult {
   color: white;
   padding: 3px;
}
button {
  margin-left:3rem ;
}
<h3 ></h3>

<div >
  <div >
    <div >
       <h1 >
        <span >JavaScript</span> Number guessing game</h1>

    <p >Simply enter a number between 1 - 100 then click the button</p>
    </div>
    <div >
      <div >
<div >
      <label for="guessField">Guess a number : </label><input type="text" id="guessField" >
      <input type="submit" value="Submit guess" >
    </div>

    <div >
      <p ></p>
      <p ></p>
      <p ></p>
    </div>
      </div>
    </div>  </div>
</div>   

Resource

JavaScript number guessing game

  • Related