简体   繁体   中英

How to get DataTextField of DropDownList in javascript?

I am using a DropDownList as

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

and when I select item from dropdown the DataTextField should be displayed in the textfield. For that i am using following javascript:

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

It works fine when dropdown's DataValueField is not used. But how to do desired task when DataValueField property of dropdown is also used?

Thanks in advance.

The DataValueField will populate the html <option /> tags value property, while the DataTextField will populate the text property.

When you don't specify a DataValueField the DataTextField is used for both (and vice-versa IIRC).

So in JavaScript you'll want to have the following ( note - I'm using the MS AJAX shorthand where $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');
}

Then you can do what ever you want with the results, such as putting them into a text box.

Thanks for your replys. I found answer.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM