【发布时间】:2016-02-25 18:16:24
【问题描述】:
我尝试找到一些修复程序,但似乎没有找到我正在寻找的东西。也许是我的措辞。
所以我有这个表单,一旦它使用 5 位邮政编码提交,它会检查一个数组是否匹配值,一旦它匹配我希望它显示成功消息,如果它不匹配则返回不匹配,但目前它返回消息的次数与数组一样多。我对 JavaScript 还是很陌生,所以任何帮助都将不胜感激。提前致谢!
JavaScript:
<script>
function getZip(e) {
e.preventDefault();
var zip = document.getElementById('zip').value; // Gets the value from the text field "zip" on the form.
var result = ["48650", "48611", "48746", "48614", "48706"];
for (var i = 0; i < result.length; i++) {
//console.log(result[i]);
//if (zip.length == 5 && zip == result[i]){
if (zip == result[i]) {
console.log(zip + " is = to " + result[i]);
alert('Match ' + zip);
} else if (result[i] != zip) {
alert("No Match1");
console.log(zip + " is != to " + result[i]);
} else {
alert("No Match2");
console.log(zip + " is != to " + result[i]);
}
//return false;
}
if (zip === "") { // Checks if the text field "zip" is empty, if so it returns an error message.
alert('Please enter a zip code!');
} else if (zip.length > 5) {
alert("Please enter a valid 5 digit numeric zip code.");
} else if (zip.length < 5) {
alert("Please enter a valid 5 digit numeric zip code.");
} else if (isNaN(zip)) { // Checks if the text field "zip" for alphabetic characters. The "isNaN" function is to determine if a value does not convert to a number, if so it returns an error message.
alert("Please enter a numeric value.");
}
}
</script>
表格:
<div class="searchZip">
<p>Please enter your zip code for availability</p>
<form>
<input type="text" name="zip" id="zip" placeholder="Zip Code">
<button onclick="getZip(event);">Check</button>
</form>
<p id="display"></p>
</div>
【问题讨论】:
-
@Abhitalks 也可能是 How to stop a for loop? 的副本 :)
-
虽然这不是唯一的问题,但它仍然只返回第一个结果,而不是与其他 int eh 数组匹配
标签: javascript arrays json loops for-loop