I'm using the accepted answer to this question to help me build an HTML select menu from a JSON array using jQuery.
My JSON array is passed from a PHP script as $menu and looks like this:
{ "options": [
{ "id":"7","name":"Smith, John"},
{ "id":"4","name":"Jones, Tom"}
]
}
First I build the skeleton of my select menu and insert it into the page:
var div = '<div class="row">';
var label = '<label for="employee">Employee</label>';
var select = '<select name="employee id="employee">';
var close = '</select></div>';
var menu = div + label + select + close;
$('#clicked_link').prepend(menu);
Then I try to pass the $menu array to jQuery like this:
var json = '<?php echo $menu; ?>';
Then I try to append the options to the newly created select menu, using the example from the linked question:
var options = eval('(' + json + ')');
var length = options.length;
for (var j = 0; j < length; j++)
{
var newOption = $('<option/>');
newOption.attr('id', options[j].id);
newOption.attr('name', options[h].name);
$('#employee').append(newOption);
}
The select menu is showing up as expected, but it contains no options. Can anyone see where I'm making my error(s)? Thanks in advance.
Revised to incorporate Rocket's solution:
var json = <?php echo $menu; ?>;
var options = json.options;
var length = options.length;
for (var j = 0; j < length; j++)
{
var newOption = $('<option/>');
newOption.attr('value', options[j].id);
newOption.attr('text', options[j].name);
$('#employee').append(newOption);
}