使用JavaScript设置select标记的选定索引

Set the selected index of select tag using JavaScript

本文关键字:索引 JavaScript 设置 select 使用      更新时间:2023-09-26

如何使用java脚本设置select标记的默认选定索引?我的代码运行良好,但我无法确定默认的选定值(例如)第一个值。

  var CompanySelect = document.getElementById("ManagingCompaniesSelect");
if (result && result.length > 0) {
    CompanySelect.options[CompanySelect.options.length] = new Option(_seletCompany, -1);
    for (var i = 0; i <= result.length-1; i++)
    { CompanySelect.options[CompanySelect.options.length] = new Option(result[i].ManagingCompanyName, result[i].MangingCompanyGUId); }
}


var txtManagingCompany = '#ManagingCompaniesSelect' + ' option[value=-1]';
$(txtManagingCompany).attr("selected", "selected");

您可以使用selectedIndex属性。

示例

 CompanySelect.selectedIndex = 0;
 // will select the first option by default and so on..