我使用 DropDownList 作为
<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 属性也被使用时,如何执行所需的任务?
提前致谢。
最佳答案
DataValueField 将填充 html <option />
标记值属性,而 DataTextField 将填充文本属性。
当您不指定 DataValueField 时,DataTextField 将用于两者(反之亦然 IIRC)。
因此,在 JavaScript 中,您需要具有以下内容(注意 - 我正在使用 MS AJAX 简写,其中 $get === 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');
}
然后您可以对结果执行任何您想要的操作,例如将它们放入文本框中。
关于c# - 如何在javascript中获取DropDownList的DataTextField?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/370944/