1

I am getting this list from server(php):

["Ak-Bulak","Balykchy","Batken"]

how can i access it and put into selects options thru js, what i tried is:

for (var i in data) {
   $('#cities').append('<option>'+ data[i] +'</option>');
}

it putting every chars as one option: <option>[</option>, <option>"</option>...

how can i access each element here? not each char..

rahularyansharma
  • 11,046
  • 17
  • 77
  • 129
doniyor
  • 34,368
  • 52
  • 164
  • 248

5 Answers5

3

If it's a var on your php page something like this would work

for (var i in <?php echo '["Ak-Bulak","Balykchy","Batken"]'; ?>) {
   $('#cities').append('<option>'+ i +'</option>');
}
slinky2000
  • 2,593
  • 1
  • 13
  • 12
2

It seems that you don't have a list, you have a string. So first, parse that string:

var list = JSON.parse('["Ak-Bulak","Balykchy","Batken"]')

And then, loop over it as you already did, or without using keys:

for (var i=0; i<list.length; i++) {
    $('#cities').append('<option>'+ data[i] +'</option>');
}
Salvatorelab
  • 11,133
  • 6
  • 52
  • 75
  • 1
    If the assumption that the user is dealing JSON is correct (and I figure it is), this is the proper answer. If you need to support a browser which does not natively support the JSON API, you can download `json2.js` from https://github.com/douglascrockford/JSON-js and load it on your page before the code which needs to parse JSON. – JAAulde May 16 '13 at 11:14
  • Seems he is using jQuery so he can use `jQuery.parseJSON` http://api.jquery.com/jQuery.parseJSON/ – Salvatorelab May 16 '13 at 11:14
  • remember to use `console.log` when strange things like this happen. You can use `console.log` with objects, and inspect them with firebug/dev tools (F12). – Salvatorelab May 16 '13 at 11:21
1

You need to parse this string as JSON first.

var buffer = eval(data)
for (var i in buffer) {
    $('#cities').append('<option>'+ buffer[i] +'</option>');
}

But if you use eval() you must be sure that input data is consistent. updated.

Maxim Khan-Magomedov
  • 1,296
  • 11
  • 14
1

Try this,

    var data='["Ak-Bulak","Balykchy","Batken"]';
    data=JSON.parse(data);


for (var i in data) {
   $('#cities').append('<option>'+ data[i] +'</option>');
 }
Shijin TR
  • 7,179
  • 9
  • 47
  • 111
0

What about:

var data=<?php echo '["Ak-Bulak","Balykchy","Batken"]'; ?>;

for (var i in data) {
   $('#cities').append('<option>'+ data[i] +'</option>');
}
Frederik.L
  • 5,372
  • 2
  • 26
  • 41