Danielle Danielle - 12 days ago 5
HTML Question

I need help to get my (input a word) to work. Using javascript or jquery

HTML CODE

<form>
Input: <input type="text" name="input" id="input"><br>
<br>
Output: <input type="text" name="output" id="output"><br>
<input type="submit" value="submit" onclick="yourGuess()" id="submit">
</form>


<div id="answer"></div>


Script

I can't figure out how to get the code to compare input to the words in the array and come out with a correct or wrong answer and put it in the div (id=answer).

function yourGuess()
{
var n = 0;
var words = ['banana', 'orange', 'apple', 'peach'];
var guess1 = document.getElementById("input").value;

//wrong answer
if (guess1 !== words) {
document.getElementById("answer").innerHTML = "Wrong!";

}
else {
//right answer
if (guess1 == words) {
document.getElementById("answer").innerHTML = "Correct!";

}
</body>

Answer

I would suggest using jQuery.inArray() if you go with jQuery:

$('#submit').on('click', function(event) {
  event.preventDefault();
  var wordsArray = ['banana', 'orange', 'apple', 'peach'];
  var guessInput = $('#input').val();
	
  /* Check in Array */
  if($.inArray(guessInput, wordsArray) !== -1) {
    $('#answer').text('Correct!');
  } else {
    $('#answer').text('Wrong!');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  Input:
  <input type="text" name="input" id="input">
  <br>
  <input type="submit" value="submit" id="submit">
</form>
<div id="answer"></div>

Or you can go with JavaScript Array indexOf() Method

function yourGuess() {
  var wordsArray = ['banana', 'orange', 'apple', 'peach'];
  var guessInput = document.getElementById('input').value;
  
  /* Check indexOf() */
  if(wordsArray.indexOf(guessInput) !== -1) {
    document.getElementById('answer').innerHTML = 'Correct!';
  } else {
    document.getElementById('answer').innerHTML = 'Wrong!';
  }
}
<form>
  Input:
  <input type="text" name="input" id="input">
  <br>
  <input type="submit" value="submit" id="submit" onclick="yourGuess()">
</form>
<div id="answer"></div>

Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false, but 0 !== false), to check for the presence of value within array, you need to check if it's not equal to (or greater than) -1.