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");
}
}
}
city2check
refers to your input element. You want city2check.value
to get its value.
Additionally:
</input>
isn't a thing. Remove it. document.getElementById('city2check')
rather than just city2check
to prevent ambiguity. 变量city2check
包含任何值,因此比较始终为false。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.