Reputation: 3257
I am trying to read something from a JSON object with JavaScript and jQuery. But I keep getting thrown an exception that "code" is not set. What I want to do, is read a country code from a string, and pre fill an input field depending on what the string is.
This is my code:
<input type="text" name="country">
<script>
$(document).ready(function () {
var countryData = [{
"id": 23,
"code": "DK",
"country": "Danmark",
"phone_phoneext": "+45"
}, {
"id": 24,
"code": "SE",
"country": "Sverige",
"phone_phoneext": "+46"
}, {
"id": 25,
"code": "NO",
"country": "Norge",
"phone_phoneext": "+47"
}];
var countryCookie = "DK"; //Will be read from a cookie later
function getCountryByCookie(countryCode) {
return countryData.filter(
function (countryData) {
return countryData.code == code
});
}
try {
var foundCountryCookie = getCountryByCookie(countryCookie);
$("input[name=country]").val(foundCountryCookie[0].country);
} catch (e) {
console.log(e);
}
});
</script>
Upvotes: 0
Views: 46
Reputation: 6014
Thats because you never declare or set the variable code
.
function getCountryByCookie(countryCode) {
return countryData.filter(
function(countryData){return countryData.code == countryCode} //countryCode instead of just code
);
}
Upvotes: 4