Reputation: 1574
I have a json array which looks like this
[{
"": "Select your State/Region"
}, {
"BAL": "Balkh"
}, {
"BAM": "Bamian"
}]
I am trying to get the values out of it using jquery, but i can't seem to loop through.
This is what I've tried
var value = $(this).val();
var url = '{{ route('getstatesjson') }}';
$.getJSON(url, { state: value }, function(obj) {
for (var i = 0, len = obj.length; i < len; i++) {
}
});
but i can't seem to pull any of the objects out. The idea is that i can use the first value as the value and the second value as the text in the select.
Upvotes: 2
Views: 43
Reputation: 72269
You have to do it like below:-
$.getJSON(url, { state: value }, function(obj) {
var html = '';
$.each(obj,function(key,value){
$.each(value,function(k,v){
html +="<option value='"+k+"'>"+v+"</option>";
});
});
$('put select-box id or class').html(html);
});
DEMO EXAMPLE:-
obj = [{
" ": "Select your State/Region"
}, {
"BAL": "Balkh"
}, {
"BAM": "Bamian"
}];
var html = '';
$.each(obj,function(key,value){
$.each(value,function(k,v){
html +="<option value='"+k+"'>"+v+"</option>";
});
});
$('#updateOptions').html(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="updateOptions"></select>
Note:- I think "": "Select your State/Region"
need to be " ": "Select your State/Region"
so that value for this option become empty like value=" "
Upvotes: 2