Jammer Jammer - 1 year ago 55
jQuery Question

Add items to drop-down box

I can't seem to find the correct syntax to get this working:

$.get('/templates/mytemplate.html', function (template) {

$(template).find('select').append($("<option />").val(0).text('Please select ...'));
$.each(dashboard.myArray, function () {
$(template).find('select').append($("<option />").val(this.Id).text(this.Text));

The template variable is just a string of html like:

"<form class="user-item">
<select class=".sc" name="context" />
<input type="hidden" name="id"/>
<input type="hidden" name="date"/>

I've tried selecting the
item on name
and using a class selector like
as well ... none seem to work but I've got similar code working fine elsewhere. Very confused.

Answer Source

The problem is template is a string. in your case you are creating a new jQuery wrapper for that element every time and manipulating it but that does not actually change the contents of the string in template, it just changes another in memory object

You need to create a reference to a new jQuery wrapper for template then do the dom manipulation using that reference and at the end append it to the container element

$.get('/templates/mytemplate.html', function (template) {
    var $template = $(template);
    $template.find('select').append($("<option />").val(0).text('Please select ...'));
    $.each(dashboard.myArray, function () {
        $template.find('select').append($("<option />").val(this.Id).text(this.Text));

Demo: Problem, Solution

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download