Jquery 检查用户输入值是否与JSON条目ID/值匹配
下面是我的JSON(每个数据条目/集合)通过/Jquery 检查用户输入值是否与JSON条目ID/值匹配,jquery,json,Jquery,Json,下面是我的JSON(每个数据条目/集合)通过/locations.JSON的样子 { "20101":{ // I use zip value as an entry ID, so check if this matches .val() "Zipcode":"20101", "City":"", "Primary State":"Virginia", "Lotto":"49530", "County":"Loudoun" } // .... etc m
locations.JSON的样子
{
"20101":{ // I use zip value as an entry ID, so check if this matches .val()
"Zipcode":"20101",
"City":"",
"Primary State":"Virginia",
"Lotto":"49530",
"County":"Loudoun"
} // .... etc more entries
以下是我的web表单HTML标记:
<form action="">
<input type="text" name="Zipcode" id="Zipcode" value="" maxlength="5" placeholder="Zipcode">
<input type="button" name="submit" id="submit" value="Submit">
</form>
最新尝试:(但它总是以失败的形式返回)
试试这个。如果你在做for循环,那么一旦它通过,你就必须打破它。
但是,执行for循环是浪费时间,请尝试查找变量是否存在
看看下面
$(document).ready(function() {
$("#submit").click(function() {
var ZipSearch = $("#Zipcode").val();
console.log(ZipSearch)
var myjson;
$.getJSON("locations/locations.json", function(json) {
myjson = json;
if (myjson[ZipSearch]){// if exist
console.log("Pass")
console.log(myjson[ZipSearch]);
$('.error').hide();
}else {
console.log("Fail")
$('.error').show();
}
});
});
});
那么,你的if语句的尝试在哪里呢?您没有显示在getJSON回调中使用该值的尝试。请记住,您必须在getJSON回调中执行该条件逻辑。
$(document).ready(function() {
$("#submit").click(function() {
var ZipSearch = $("#Zipcode").val();
console.log(ZipSearch)
var myjson;
$.getJSON("locations/locations.json", function(json) {
myjson = json;
for (var key in json) {
// console.log(key);
if (key === ZipSearch) {
console.log("Pass")
console.log(myjson[ZipSearch]);
$('.error').hide();
} else {
console.log("Fail")
$('.error').show();
}
}
});
});
});
$(document).ready(function() {
$("#submit").click(function() {
var ZipSearch = $("#Zipcode").val();
console.log(ZipSearch)
var myjson;
$.getJSON("locations/locations.json", function(json) {
myjson = json;
if (myjson[ZipSearch]){// if exist
console.log("Pass")
console.log(myjson[ZipSearch]);
$('.error').hide();
}else {
console.log("Fail")
$('.error').show();
}
});
});
});