javascriptc#asp.netuser-controlsclientid

How to acquire the ClientID of User Control Drop Down List


I have created a user control containing a drop down list. I am unable to acquire the ClientID in order to get the selected value or text.

Implementation

<%@ Register Src="~/Common/Controls/ReasonPicker.ascx"
TagName="ReasonPicker" TagPrefix="uc2" %>

<td>
<uc2:ReasonPicker ID="ReasonPicker" Width="100%" AutoPostBack="false"
runat="server" AddAny="True" />
</td>

ascx file

<%@ Control Language="C#" AutoEventWireup="true"
CodeBehind="ReasonPicker.ascx.cs"
Inherits="********.********.com.web.Common.Controls.ReasonPicker" %>

<div runat="server" id="Reasons">
<asp:DropDownList runat="server" AutoPostBack="true" Width="158"
ID="ReasonPickerDropDown"OnSelectedIndexChanged="
ReasonPickerDropDown_SelectedIndexChanged"
onchange="ChangeVisibility(this)">
</asp:DropDownList>
</div>
</div>

I tried the following methods but no luck

var reason = $('<%=ReasonPicker.ClientID%> option:selected').text();
var reason = $('<%=ReasonPickerDropDown.ClientID%> option:selected').text();

Currently I am using the below code segment in order to complete the task.

var reason =
$('#ctl00_MainContentPlaceHolder_ReasonPicker_ReasonPickerDropDown
option:selected').text();

I need to do this task by accessing its ClientID using <%ClientID%>. Help Me. Thanks


Solution

  • Try this

    var reason = $('<%=ReasonPicker.ClientID%>').find('select option:selected').text();
    

    OR

    var ddlReason =  document.getElementById('<%=ReasonPicker.FindControl("ReasonPickerDropDown").ClientID %>');
    var reason = ddlReason.options[ddlReason.selectedIndex].text;