使用Javascript设置Asp:下拉列表

Using Javascript to set a Asp:Dropdownlist

本文关键字:下拉列表 Asp 设置 Javascript 使用      更新时间:2023-09-26

我尝试了各种方法来设置下拉列表无效。在开发人员工具中,我可以看到selectedIndex的适当更改,我可以看到选项节点从选定的false更改为选定的true。但是当弹出模式打开时,下拉列表显示第一个选项,它是空白的。如果我关闭并重新打开弹出窗口,它将显示我手动选择的任何内容。我如何以编程方式设置下拉列表值?

标记

   <%--Address Popup--%>
    <div id="location_modal" class="reveal-modal modal_location" data-reveal>
    <fieldset>
    <legend>Locations(Update/New)</legend>
      <div class="row">
        <div class="large-4 columns">
           <asp:Label ID="Label4" runat="server">Location:*</asp:Label>
           <asp:DropDownList ID="ddLocationNames" runat="server" class="input_ddllocationName"></asp:DropDownList>
       </div>

Js

    locationNameId = 'MainContent_lvAddresses_lblAddressLocation_' + g_index
    locationName = document.getElementById(locationNameId).innerHTML;
    var select = document.getElementById("MainContent_ddLocationNames");
    for (var i = 0; i <select.options.length; i++){
        if(select.options[i].innerHTML == locationName){
            //select.selectedIndex = i;
            //$(".input_ddllocationName").selectedIndex = i;
            select[i].selected = true;
            }
            else{
            select[i].selected = false;
            }
        }

Droplistid: MainContent_ddLocationNames

1. selected="selected" value="" 
2. value="1">TESTING            
3. value="2">TESTING AGAIN      
4. value="3">MY FAVORITE LOCATION 
5. value="4">MGM GRAND BALLROOM A

如果页面上有jQuery:

$(".input_ddllocationName").val(locationName);

或locationNameId,取决于哪个是选项的值属性

如果你使用的是核心JavaScript,那么这应该可以工作。

locationName = document.getElementById(locationNameId).innerHTML;
var select = document.getElementByClassName("input_ddllocationName")[0];
for (var i = 0; i <select.options.length; i++){
    if(select.options[i].innerHTML == locationName){
        select.selectedIndex = i;
        // OR select.value = select.options[i].value;
    }
    else{
        select[i].selected = false;
    }
}

由于基础,下拉列表有一些'特殊'标记。

在Js中,我必须添加一些额外的代码行。感谢Google开发工具!
//Find out which row should be selected
var indexSave = 0;
for (var i = 0; i<select.options.length; i++){
    if(select.options[i].innerHTML == locationName){
        indexSave = i;
        break;
        }
    }
   //Set the current node to the Location Name
   $('#MainContent_ddlLocationName').next().children().first().text(locationName);
   //Remove all selections
    $('.input_ddlLocationName ul li').each(function() {
        $(this).removeClass("selected");
    });
    //Select the Location Name based on index
    var selectLi = indexSave + 1;
    $('.input_ddlLocationName ul li:nth-child(' + selectLi + ')').addClass("selected");