2017-05-09 62 views
0

我有一個JSON元素,其中包含與「區域」關聯的一堆不同的郵政編碼。我想這樣做是允許用戶提交他們的郵政編碼,檢查JSON元素中存在的郵政編碼,然後報告「區」它屬於的,如果它:檢查輸入中的郵政編碼是否存在於JSON中並獲得類別

var zones = [{ 
 
    "zone": "one", 
 
    "zipcodes": ["69122", "69125", "69128", "69129"] 
 
    }, 
 
    { 
 
    "zone": "two", 
 
    "zipcodes": ["67515", "67516", "67518", "67521"] 
 
    } 
 
]; 
 

 
$(function() { 
 
    $('#userZip').submit(function(e) { 
 
    e.preventDefault(); 
 
    var userZip = $('input[type="text"]').val(); 
 
    // Check if zip exists in JSON and report which zone it belongs to 
 
    }); 
 
});
i { 
 
    display: block; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form id="userZip"> 
 
    <i>Enter zip code "69122" as an example</i> 
 
    <input type="text" placeholder="zip" /> 
 
    <input type="submit" /> 
 
</form>

+1

檢查了這一點OP - http://stackoverflow.com/a/6384527/7226958 這幾乎是相同的情況 –

回答

3

您可以使用Array.find

var zones = [ 
 
    { 
 
\t \t "zone": "one", 
 
\t \t "zipcodes": ["69122", "69125", "69128","69129"] 
 
\t }, 
 
\t { 
 
\t \t "zone": "two", 
 
\t \t "zipcodes": ["67515", "67516", "67518", "67521"] 
 
\t } 
 
]; 
 

 
$(function() { 
 
    $('#userZip').submit(function(e) { 
 
    e.preventDefault(); 
 
    var userZip = $('input[type="text"]').val(); 
 
    // find the first zone with the userZip inside its zipcodes list 
 
    var zone = zones.find(function(zone) { 
 
     return zone.zipcodes.indexOf(userZip) > -1; 
 
    }); 
 
    alert("Zone: " + zone.zone); 
 
    }); 
 
});
i { 
 
    display:block; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form id="userZip"> 
 
    <i>Enter zip code "69122" as an example</i> 
 
    <input type="text" placeholder="zip" /> 
 
    <input type="submit" /> 
 
</form>

+0

這很好,謝謝! – user13286

相關問題