0

I am trying to make a select with the option value and text coming from two separate arrays (one is called like_list and the other like_list_name). The '$.each' joins two arrays and makes list of options. When I look in console.log I can see the options looking good:

$.each(like_list, function(i, item) {
console.log('<option value="' + like_list[i] + '">' + like_list_name[i] + '</option>');
});

But when I name the output as 'optionlist' and try to put 'optionlist' into the div 'friendselect' with Inner HTML it doesn't work:

var optionlist = $.each(like_list, function(i, item) {
'<option value="' + like_list[i] + '">' + like_list_name[i] + '</option>';
});

document.getElementById('friendselect').innerHTML = '[select]' + optionlist + '[/select]';

Is there anyway to get this select box into the 'friendselect' div? NOTE: i USED '[' because the side arrow wasn't working.

  • I found and used this http://stackoverflow.com/questions/170986/what-is-the-best-way-to-add-options-to-a-select-from-an-array-with-jquery – Jarrod Dean Jun 12 '14 at 23:15

2 Answers2

2

You should try with map function:

var optionlist = $.map(like_list, function(i, item) {
  return '<option value="' + like_list[i] + '">' + like_list_name[i] + '</option>';
}).join('');

document.getElementById('friendselect').innerHTML = '<select>' + optionlist + '</select>';
hsz
  • 148,279
  • 62
  • 259
  • 315
-1

$.each() doesn't return the values in it's function, you will have to add them toghether yourself.

The best thing you can do is add the options to the select in the each loop like so:

$.each(like_list, function(i, item) {
$("#friendselect").append('<option value="' + like_list[i] + '">' + like_list_name[i] + '</option>');
});
Jerodev
  • 32,252
  • 11
  • 87
  • 108