Sean Taylor
Sean Taylor

Reputation: 25

Puzzling behavior from IF ( ) statement

I'm a total n00b to JavaScript and fully expect this is something appallingly obvious but I cannot understand why this if ( ) statement is not producing the correct results.

No matter how many characters I input the function returns 'yes' to the console whether 'word' is < or > 2. IF (ha!) anyone can shed any light on this it's greatly appreciated. Code below:

var word = document.getElementById('wordChoice').value;  

function flipChk () {

if (word.length < 2) {
    console.log('yes');

} else { 
    console.log('no');
}
}

See the fully implemented code here: http://supsean.com/supsean/flipr/flipr.html

Upvotes: 0

Views: 83

Answers (2)

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21575

Have word be set in the function:

function flipChk () {
  var word = document.getElementById('wordChoice').value; 

  if (word.length < 2) {
    console.log('yes');
  } else {
    console.log('no');
  }
}

Your code got the value of word only on page load, which was a empty string. Which is why it's always yes.

Upvotes: 1

Justin Niessner
Justin Niessner

Reputation: 245429

Have you tried debugging your code and seeing what the value of word is when you click the button?

I'm guessing part of your problem is that you're assigning a value to word when the page loads but not reading it again when the user clicks the button.

Upvotes: 3

Related Questions