Mr. OJ Mr. OJ - 9 days ago 6
jQuery Question

Why are $.appendTo() not appending my <options> tag correctly?

Hi I have this "simple" issue bugging me. I have the following JS code building a

<select>
with options:

var sel = $('<select id="' + elemData.id + '" name="' + elemData.id + '" onchange="folderBrowser.selectChanged(this)"></select>');
app.selectedPaths = localStorage.selectedPaths;

if (app.selectedPaths) {
app.selectedPaths = JSON.parse(app.selectedPaths);
app.selectedPaths.forEach(function (arr) {
$("<option value=" + arr.path + ">" + arr.path + "</option>").appendTo(sel);
});

}
return sel;


As you see I am trying to append
<option>
elements to a
select
. I get a
option
tag with id, but not the text!
innerHTML
is blank. What am I doing wrong?

Answer

Try changing this:

$("<option value=" + arr.path + ">" + arr.path + "</option>").appendTo(sel);

To this:

$('<option value="' + arr.path + '">' + arr.path + '</option>').appendTo(sel);

value is usually quoted so try using double " and single' quotes.