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");
}
}
}
-
1FWIW, it's not a syntax issue.Felix Kling– Felix Kling2014年05月14日 15:03:35 +00:00Commented May 14, 2014 at 15:03
-
city2check is an input element not a type. === is not validating correctlystripthesoul– stripthesoul2014年05月14日 15:04:00 +00:00Commented May 14, 2014 at 15:04
2 Answers 2
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 justcity2checkto prevent ambiguity.
answered May 14, 2014 at 15:02
Niet the Dark Absol
326k86 gold badges480 silver badges604 bronze badges
Sign up to request clarification or add additional context in comments.
6 Comments
Amit Joki
more than ambiguity, it isn't cross-browser.
Niet the Dark Absol
@AmitJoki It isn't? I thought it was a compatibility thing for ancient browsers...
Amit Joki
Some browsers, for instance FF don't expose them to the global scope.
Pointy
@AmitJoki that used to be true, but Firefox 29 now works like IE always has, and like Chrome has for some time.
user3637192
could you please show me how the code should look like to display the alert("correct")?
|
the variable city2check contains no value so the comparison is always false.
answered May 14, 2014 at 15:02
Thijs Kramer
1,1378 silver badges19 bronze badges
6 Comments
Pointy
Not true in most browsers - that's the "id" of the
<input> tag so the value is a reference to the DOM element.Thijs Kramer
That's not true.
document.getElementById('city2check') is a reference to the DOM element, not the variable city2check itself.Pointy
Try it for yourself if you don't believe me.
Pointy
Well don't feel bad; personally I think that behavior is a terrible idea :)
user3637192
could someone kindly show me how to modify this entire code to get what I need please?..
|
lang-js