2013-09-10 32 views
1

我有一個未綁定的列表被填充。無法獲取動態填充的asp:dropdownlist的ID

<asp:DropDownList ID="ddlState" runat="server" style="margin-left: 81px" 
    onselectedindexchanged="ddlState_SelectedIndexChanged" 
    CssClass="styled-select"> 
</asp:DropDownList> 

<asp:DropDownList ID="ddlManagerName" runat="server" Height="22px" 
    style="margin-left: 08px; width:auto;" ></asp:DropDownList> 

和運行得到一個javascript按鈕上的ID使用點擊

function validateDynamic() { 

    var getState = document.getElementById('<%=ddlState.ClientID %>').selectedIndex; 
    var getManager = document.getElementById('<%=ddlManagerName.ClientID %>').selectedIndex; 
    if(getState == 0) 
    { 
     alert("State is a required field !"); 

    } 

    if(getManager == 0) 
    { 
     alert("Manager Name is a required field !"); 

    } 

    return false; 
} 

我已經試過大部分從視圖源的以下

名= 「ctl00 $搜索Maincontent $ ddlState」 id =「MainContent_ddlState」都是名稱和ID,我得到的所有對象都是未定義的。

這裏是按鈕的代碼獲取調用該函數

<asp:Button id="btnSaveTM" runat="server" Text="Add Team Member" class="btn" onmouseover="this.className='btn btnhov'" 
    onmouseout="this.className='btn'" style=" Height:34px" OnClientClick="validateDynamic();" 
    onclick="btnSaveTM_Click" UseSubmitBehavior="true" CausesValidation="true" /> 

,當我調試,我得到的getState和管理者爲未定義。任何幫助表示讚賞。

+2

你知道的document.getElementById( '<%= ddlState.ClientID%>')實際上得到的元素? – Carter

+0

你的兩個元素都可見嗎? –

+0

您需要獲取ID或選定的值。 – Sasidharan

回答

0

你看過服務器返回的源代碼嗎?腳本中的ID是否與渲染元素的ID匹配?另外像<%=ddlState.ClientID %>這樣的代碼塊不能在外部腳本文件中工作。爲了讓他們工作,你必須在頁面上嵌入腳本。他們只能使用.aspx文件。 你也可以嘗試獲取控制檯上的元素(如Chrome DevTools)。如果您返回了正確的元素,您可以將其與腳本中的行進行比較。

2

使用此得到下拉列表中選擇的值:

var getState = (document.getElementById('<%= ddlState.ClientID %>') 
        .options[document.getElementById("<%=ddlState.ClientID%>") 
        .selectedIndex].value)