0

Hi I'm following a tutorial on JS For Loop and trying something which I can't make it to work. I'm not sure what i'm missing to display the alert after checking the array in the loop. Please help me to figure out this very simple syntax issue. Thank you!

HTML

<input type= "text" id="city2check"></input>
<button type="submit" onClick="myCity()">Check</button>

JS

function myCity() {
    var cleanestCities = ["Cheyenne", "Santa Fe", "Tucson", "Great Falls", "Honolulu"];     
        for (var i = 0; i < cleanestCities.length; i++) {
            if (city2check === cleanestCities[i]) {
                alert("correct");
            }
    }
}
2
  • 1
    FWIW, it's not a syntax issue. Commented May 14, 2014 at 15:03
  • city2check is an input element not a type. === is not validating correctly Commented May 14, 2014 at 15:04

2 Answers 2

4

city2check refers to your input element. You want city2check.value to get its value.

Additionally:

  • </input> isn't a thing. Remove it.
  • Prefer document.getElementById('city2check') rather than just city2check to prevent ambiguity.
Sign up to request clarification or add additional context in comments.

6 Comments

more than ambiguity, it isn't cross-browser.
@AmitJoki It isn't? I thought it was a compatibility thing for ancient browsers...
Some browsers, for instance FF don't expose them to the global scope.
@AmitJoki that used to be true, but Firefox 29 now works like IE always has, and like Chrome has for some time.
could you please show me how the code should look like to display the alert("correct")?
|
0

the variable city2check contains no value so the comparison is always false.

6 Comments

Not true in most browsers - that's the "id" of the <input> tag so the value is a reference to the DOM element.
That's not true. document.getElementById('city2check') is a reference to the DOM element, not the variable city2check itself.
Try it for yourself if you don't believe me.
Well don't feel bad; personally I think that behavior is a terrible idea :)
could someone kindly show me how to modify this entire code to get what I need please?..
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.