Jammer Jammer - 5 months ago 11
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));
});
$('#new-items').append(template);
});


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"/>
<form>"


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

Answer

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));
    });
    $('#new-items').append($template);
});

Demo: Problem, Solution