如何将选项对象选择为默认值
How to make an Option Object be selected as the Default Value
以下代码在加载页面之前触发。现在,我已经设法用值填充了一个选择。但我不确定如何使第一个值成为取消默认的选定值。
$(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中出现的默认选项。
将SelectDropDown
的selectedIndex
设置为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);
相关文章:
- Selectize选择默认值
- 在多选下拉列表中选择默认值
- 在 Angular JS 中为 ng 选项选择默认值
- 如何从 AngularJS 的下拉框中设置选择默认值
- 当 ng-model 和 ng-options 引用不同的对象时,如何使用 ng-init 在选择框中选择默认值
- 为“角度”中的下拉列表选择默认值
- 在 html 下拉列表中选择默认值
- 在angularjs中选择,而不是选择默认值
- easyUI数据网格内部编辑组合框无法选择默认值
- 角度设置ui从另一个控制器中选择默认值
- 在ng-options中选择默认值
- 防止在ASP.NET中选择默认值时下拉的“选定索引更改”事件
- 我的javascript函数在下拉菜单中选择默认值有什么问题?
- 动态选择并选择默认值
- 当从下拉菜单中选择默认值时,隐藏复选框.[Angular js]
- Angularjs使用ng-options选择默认值
- 不能在AngularJS中使用ng-model和ng-repeat或ng-select在下拉菜单中选择默认值
- 在单选按钮angularjs中选择默认值
- Angular.js:从ID中选择默认值
- AngularJS ng选项在选择选项后选择默认值导致:“;TypeError:无法读取属性'[属性]'