I have the following test.json :
{"countries":[{"countryCode":"US","officialName":"UNITED STATES OF AMERICA","continent":"NORTH AMERICA","currentSeason":"WINTER"},{"countryCode":"AR","officialName":"ARGENTINA","continent":"SOUTH AMERICA","currentSeason":"SUMMER"}]}
And the following html/jQuery that populates a dropdown with the officialName
values from the JSON data:
<html>
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<script src="jquery.js"></script>
</head>
<body>
<div>
<select id="countries"></select>
<br>
<textarea id="detailsbox" rows="4" cols="50">
</textarea>
</div>
</body>
<script type="text/JavaScript">
$(document).ready(function() {
var $select = $('#countries')
$.getJSON('test.json',function(translations){
$select.html('');
//iterate over the data and append a select option
$.each(translations.countries, function(key, val){
$select.append('<option id="' + val.countryCode + '">' + val.officialName + '</option>');
})
});
});
</script>
</html>
My question is, how can I access the other dependent data (like currentSeason, countryCode, continent) based on the country selected, and fill in the detailsBox
textarea with that data?
Thank you.
var translations = { "countries": [{ "countryCode": "US", "officialName": "UNITED STATES OF AMERICA", "continent": "NORTH AMERICA", "currentSeason": "WINTER" }, { "countryCode": "AR", "officialName": "ARGENTINA", "continent": "SOUTH AMERICA", "currentSeason": "SUMMER" }] } var $select = $('#countries') $.each(translations.countries, function(key, val) { $select.append('<option id="' + val.countryCode + '">' + val.officialName + '</option>'); }) $select.change(function() { var countrycode = $("option:selected",this).attr('id'); $.each(translations.countries, function(key, val) { console.log(val.countryCode) console.log(countrycode) if(val.countryCode == countrycode) $("#detailsbox").text("season is " +val.currentSeason) }) }).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <select id="countries"></select> <br> <textarea id="detailsbox" rows="4" cols="50"> </textarea> </div>
Quick and dirty using Array.filter
to find the selected country after one is selected.
var $select = $('#countries');
// setting <option value="..."> as opposed to <option id="...">
$.each(translations.countries, function(key, val) {
$select.append('<option value="' + val.countryCode + '">' + val.officialName + '</option>');
});
$select.change(function() {
var code = $(this).val();
var country = translations.countries.filter(function(value) {
return value.countryCode == code;
})[0];
console.log(country);
});
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.