سؤال

I have the following script inside my Razor view engine :-

else if ($("#ChoiceTag").prop("checked")) {
                    $.getJSON("@Url.Content("~/Switch/LoadCSTag")",
                    function (CSData) {
                        var select = $("#GeneralCSID");
                        select.empty();
                        select.append($("<option/>", {
                            value: null
                        }));
                        $.each(CSData, function (index, itemData) {

                            select.append($('<option/>', {
                                value: itemData.Value,
                                text: itemData.Text
                            }));
                            select.val('@Model.Switch.ConsoleServerID');
                        });
                    });
                }

I was expecting that once the Jquery function runs, to append the "<option/>" option inside the dropdown, but currently an empty record will be displayed at the beginning of the drop down list, instead of the "<options>" text. Can anyone advice what might be the problem ? Thanks

هل كانت مفيدة؟

المحلول

select.append($("<option/>", {
   value: null
}));

This is your addition of the dummy option in the selectlist.

But you never specified what text should be displayed on that item. You can set it the exact same way you already set the text property of the items below (which, as per your comment, are already loaded correctly)

select.append($("<option/>", {
   value: "", //I prefer an empty string, not sure if null is valid
   text: "Select an option..."
}));

Update

Your quote:

displayed at the beginning of the drop down list, instead of the "<options>" text

I don't know what you mean by "<options>" text. Do you literally mean to put the string <options> as the text of that static option? I used "Select an option..." as an example, but you can choose any string you want.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top