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,156
  • 18
  • 79
  • 135
doniyor
  • 36,596
  • 57
  • 175
  • 260
  • How are you getting this list? is it a php var on your php page? – slinky2000 May 16 '13 at 11:11
  • Please don't use [`for .. in`](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea) with arrays. – Yoshi May 16 '13 at 11:17

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,663
  • 1
  • 15
  • 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,614
  • 6
  • 53
  • 80
  • 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,326
  • 12
  • 15
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,516
  • 10
  • 55
  • 122
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,522
  • 2
  • 29
  • 41