toing_toing
toing_toing

Reputation: 2442

Populate dropdown from 2 dimensional array in jquery

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.

Upvotes: 1

Views: 1273

Answers (1)

dfsq
dfsq

Reputation: 193261

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>

Upvotes: 2

Related Questions