如何将选项对象选择为默认值

How to make an Option Object be selected as the Default Value

本文关键字:选择 默认值 对象 选项      更新时间:2023-09-26

以下代码在加载页面之前触发。现在,我已经设法用值填充了一个选择。但我不确定如何使第一个值成为取消默认的选定值。

$(document).on('pagebeforeshow', '#searchpage',
//This function is the whole function that runs when the pagebefore event occurs
function () {
    //This reads the universities from the api we created
    $.getJSON(AddressAccess + "Home/university/format/json",
    function (data) {
        //The data is sent back in a collection of objects. We need to extract each object and do relative operations
        for (var i = 0; i < data.length; i++) {
            var university = data[i];
            var SelectDropDown = document.getElementById("searchuniversity");
            var NewOption = new Option(university.Name, university.UniverstiyID);
            if (i == 1) {
                SelectDropDown.add(NewOption, Selected);
            } else {
                SelectDropDown.add(NewOption);
            }
        };
    });
});

现在,如果我使用SelectDropDown.add(NewOption,Selected);,那么在select中只有一个选项作为选项,而我想要的是将从json数据中读取的第一个选项作为select中出现的默认选项。

SelectDropDownselectedIndex设置为1:

if (i == 1) {
  SelectDropDown.add(NewOption);
  SelectDropDown.selectedIndex = 1;
}

如果您真正谈论的是选项列表中的第一个选项,那么selectedIndex应该为0。select元素的options阵列是基于零的。

[根据您的评论编辑]:
可能CCD_ 7已经包含空白选项。尝试:

if (i < 1) {
  SelectDropDown.options.length = 0;
  SelectDropDown.add(NewOption);
  SelectDropDown.selectedIndex = 0;
}

只需将元素的defaultSelected属性设置为true:

var newOption = new Option(university.Name, university.UniverstiyID);
newOption.defaultSelected = true;

或者使用Option构造函数的参数:

var newOption = new Option(university.Name, university.UniverstiyID, true, true);