开发者

Adding options to a dynamically loaded select

Which is the best way to add <option>...</option> to a select that has been dynamically added to the dom?

I mean at a generic <select> that has been added subsequently an ajax call. I would like to add the option before showing the select element.

thanks!

EDIT

This is the function that I have

$.ajax({
    type: "get",
    url: baseUrl + 'MyService.asmx/NewReferent',
    data: JSON.stringify({}),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        // Get the referent item from the webservice
        var referent = msg.d;
        // Render the template with the Referent data
        var referentTemplate = $("#referentTemplate").tmpl(referent);
        //add button style
        $(".button", referentTemplate).button();
        //Show the Dialog
        $("#referent-dialog").empty().html(referentTemplate).dialog('open');
    }
}); 

This is the code that I have to get the options from the server

$.getJson(baseUrl + 'MyService.asmx/GetReferentTypes', function (data) {
    $.each(data, function (key, value) {
        $('#select_id').append($("<option></option>").attr("value", key).text(value));
    });
});

EDIT 2

Unfortunately I am not able to understand what's going on with my code. With some little modification to the code of @Raynos I have been able to receive the following JSON data from the server

{"d":
    [
        {"__type":"Full.Namespace.Path.ReferentType","ReferentTypeID":1,"Description":"option1"},
        {"__type":"Full.Namespace.Path.ReferentType","ReferentTypeID":2,"Description":"option2"}
    ]
}

that is not parsed correctly from my $.each() function call. I have two question now:


$("<select>").append(
    $("<option>" , {
        text: "foo",
        value: "bar"
    })
).appendTo("#container");

The trick is to append the options before you append the select to something.

Alternatively you can make sure to hide the select before you add it to the DOM.

pseudo code:

$.when(ajax).then(function(html) {
    var foo = $(html);
    foo.find("select.SomeClass").hide();
    ...
});

...

$("select.SomeClass").append($("<option>")).show()

[[Edit]]

Use a simple bit of $.when magic to make sure they happen in the write order. I.e. the select template is created then the options are appended

$.when(
    $.ajax({
        type: "get",
        url: baseUrl + 'MyService.asmx/NewReferent',
        data: JSON.stringify({}),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            // Get the referent item from the webservice
            var referent = msg.d;
            // Render the template with the Referent data
            var referentTemplate = $("#referentTemplate").tmpl(referent);
            //add button style
            $(".button", referentTemplate).button();
            //Show the Dialog
            $("#referent-dialog").empty().html(referentTemplate).dialog('open');
        }
    }); 
}).then(function() {
    $.getJson(baseUrl + 'MyService.asmx/GetReferentTypes', function (data) {
        $.each(data, function (key, value) {
            $('#select_id').append($("<option></option>").attr("value", key).text(value));
        });
    });
});

[[Edit 2]]

Give your sample JSON structure

$.each(data.d, function (key, value) {
    $('#select_id').append(
        $("<option></option>")
          .attr("value", value.ReferentTypeID)
          .text(value.Description)
    );
});

Would generate

<option value="0">option1</option>
<option value="1">option2</option>


This simple answer may be help you,

var selectField = $('#' + id_of_field);
var empIds = [101, 102, 103];
var empNames = ['X', 'Y', 'Z'];
var options = '';
selectField.empty();
for ( var i = 0, len = empIds.length; i < len; i++) {
    options += '<option value="' + empIds[i] + '">' + empNames[i] + '</option>';
}
selectField.append(options);    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜