2

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.

2
  • 1
    I think you should try JSON.parse to get the value Commented Sep 12, 2017 at 4:03
  • Sorry for the delay. Took me a while to come back to the website. Commented Sep 13, 2017 at 1:00

1 Answer 1

2

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=" "

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.