How to get DataTextField from DropDownList in javascript?

I am using DropDownList like

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

      

and when I select an item from the dropdown, the DataTextField should appear in the textbox. I use the following javascript for this:

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 with DataValueField dropdown. But how do you do the desired task when the dropdown's DataValueField property is also used?

Thanks in advance.

0


source to share


2 answers


The DataValueField will populate the value property of the html tags <option />

and the DataTextField will populate the text property.

If you don't specify a DataValueField, then DataTextField is used for both (and vice versa IIRC).

So in JavaScript you want to have the following ( note - I'm using 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 whatever you want with the results, such as putting them in a text box.

+3


source


Thank you for your responses. I found the answer.



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

      

0


source







All Articles