1

I have the following dropdown slect:

<select id="start" onchange="calcRoute();"></select>

I need to populate this with values I get from a Javascrippt array of this type:

{"name":"Hotel1","address":"Bondi Beach","lat":"6.369869","lng":"80.042055","thumb_path":"img\/hotel1.jpg"},{"name":"Hotel2","address":"Coogee Beach","lat":"6.025822","lng":"80.305727","thumb_path":"img\/hotel2.jpg"},{"name":"Hotel3","address":"Cronulla Beach","lat":"6.691994","lng":"79.928771","thumb_path":"img\/hotel3.jpg"},{"name":"Hotel4","address":"Manly Beach","lat":"6.887130","lng":"80.093420","thumb_path":"img\/hotel4.jpg"},{"name":"Hotel5","address":"Maroubra Beach","lat":"7.362609","lng":"79.825005","thumb_path":"img\/hotel5.jpg"}

I tried the following, but it doesnt work.

for (i = 0; i < locations.length; i++) {
    $('#start select').append('<option value=' + locations[i]['name'] + '>' + locations[i]['name'] + '</option>');
    alert("sdgsfg");
}

Please suggest a fix.

Tushar
  • 85,780
  • 21
  • 159
  • 179
toing_toing
  • 2,334
  • 1
  • 37
  • 79

1 Answers1

2

The selector $('#start select') will select the <select> element inside the #start element which not work as the id of the select itself is start. To select the element correctly use

$('#start') // or $('select#start')

It's better not to mess with HTML strings. You could use Option constructor to create new option element.

var locations = [{"name":"Hotel1","address":"Bondi Beach","lat":"6.369869","lng":"80.042055","thumb_path":"img\/hotel1.jpg"},{"name":"Hotel2","address":"Coogee Beach","lat":"6.025822","lng":"80.305727","thumb_path":"img\/hotel2.jpg"},{"name":"Hotel3","address":"Cronulla Beach","lat":"6.691994","lng":"79.928771","thumb_path":"img\/hotel3.jpg"},{"name":"Hotel4","address":"Manly Beach","lat":"6.887130","lng":"80.093420","thumb_path":"img\/hotel4.jpg"},{"name":"Hotel5","address":"Maroubra Beach","lat":"7.362609","lng":"79.825005","thumb_path":"img\/hotel5.jpg"}]

var select = $('#start')[0];
locations.forEach(function(location) {
    select.add(new Option(location.name, location.name));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="start"></select>
Tushar
  • 85,780
  • 21
  • 159
  • 179
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • You have already explained it: wrong selector `$('#start select')`. I'm just posting better version for select population, imho. – dfsq Oct 28 '15 at 09:11