2008-12-16 66 views
0

我使用一個DropDownList作爲如何在JavaScript中獲取DropDownList的DataTextField?

<asp:DropDownList 
    ID="ddlLocationName" 
    runat="server" 
    DataValueField="Guid" 
    DataTextField="LocationName" 
    AppendDataBoundItems="false" 
    AutoPostBack="false" 
    onchange="LocationChange()" 
></asp:DropDownList> 

,當我從下拉列表中DataTextField應顯示在文本字段中選擇項目。爲此,我正在使用以下javascript:

function LocationChange() 
{ 
    document.getElementById ("ctl00_mainContent_ctl02_txtEventLocation").value = document.getElementById ('ctl00_mainContent_ctl02_ddlLocationName')[document.getElementById ('ctl00_mainContent_ctl02_ddlLocationName').selectedIndex].value  
} 

當下拉的DataValueField未使用時,它工作正常。但是,如果在使用下拉的DataValueField屬性時如何執行所需的任務呢?

在此先感謝。

+0

爲什麼不顯示下拉的asp標籤有問題?任何人都可以告訴我如何顯示該標籤? – 2008-12-16 10:53:49

+0

閱讀格式化的wiki。你可能沒有把它包裝在合適的代碼塊中。爲了便於閱讀,我編輯了將JS函數編碼爲適當的代碼。 – 2008-12-16 10:56:25

回答

3

DataValueField將填充html <option />標記值屬性,而DataTextField將填充文本屬性。

當你不要指定一個DataValueField DataTextField用於兩者(反之亦然IIRC)。

所以在JavaScript中,你會希望有以下(說明 - 我使用的是MS AJAX速記其中$得到===的document.getElementById):

function LocationChange(){ 
    var ddl = $get('dropDownListId'); 
    var selectedOption = ddl.options[ddl.selectedIndex]; 
    var selectedText = selectedOption.text; 
    var selectedValue = selectedOption.value; 

    alert('Your option has a text property of ' + selectedText + ' and a value property of ' + selectedValue'); 
} 

然後,你可以做你想要什麼結果,比如把它們放到文本框中。

0

感謝您的回覆。 我找到答案。

function LocationChange() 
{ 
    document.getElementById ("ctl00_mainContent_ctl02_txtEventLocation").value = document.getElementById ('ctl00_mainContent_ctl02_ddlLocationName')[document.getElementById ('ctl00_mainContent_ctl02_ddlLocationName').selectedIndex].innerText 
} 
相關問題