使用Javascript设置Asp:Dropdownlist

时间:2014-05-22 21:24:25

标签: c# javascript jquery asp.net zurb-foundation

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

Mark Up

   <%--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;
            }
        }

Droplist     id: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

3 个答案:

答案 0 :(得分:0)

如果页面上有jQuery:

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

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

答案 1 :(得分:0)

如果您使用的是核心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;
    }
}

答案 2 :(得分:0)

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

在Js中,我不得不添加一些额外的代码行。谢谢Google Dev Tools!

//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");