Custom Web Control ID includes child ID

158 Views Asked by At

My Custom Web Control (ascx)

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="CustomAutoCompleteTextBox.ascx.cs" Inherits="UserControls_CustomAutoCompleteTextBox" ClientIDMode="Static" %>

<asp:TextBox ID="AutoCompleteTextBox" runat="server" />

Implementation on webpage EquipmentMove

<%@ Page Language="C#" MasterPageFile="~/SiteMasterPage.master" AutoEventWireup="true" CodeFile="EquipmentMove.aspx.cs" Inherits="Equipment_EquipmentMove" %>

 <Custom:AutoCompleteTextBox runat="server" ID="HardwareSNTextBox1"
            OnCloseFunction="TestOnClosefunction"
            OnFocusFunction="testme"
            OnKeyUpFunction="EquipmentSearchCheckHardwareSNLength"
            PostbackURL="EquipmentMove.aspx/HardwareSNAutoComplete"
            SpellCheck="false" />

At runtime the Custom:AutoCompleteTextBox control's client ID becomes "HardwareSNTextBox1_AutoCompleteTextBox". Resulting markup:

<input name="ctl00$cpBody$HardwareSNTextBox1$AutoCompleteTextBox" type="text" id="ctl00_cpBody_HardwareSNTextBox1_AutoCompleteTextBox" class="ui-autocomplete-input" autocomplete="off">

If I want to write a javascript called "TestOnClosefunction" on the EquipmentMove webpage and I want access this control but using it's originally entered ID of "HardwareSNTextBox1" and not "HardwareSNTextBox1_AutoCompleteTextBox" is this even possible?

Edit: I suppose if the developer using this custom web control examines the markup for the actual ID while writing their js, then that could work. Not very intuitive though.

1

There are 1 best solutions below

4
On

A very nice way is to use the server control's ClientID property, for example in your EquipmentMove ASPX page:

<form id="form1" runat="server">
    <div>
        <Custom:AutoCompleteTextBox runat="server" ID="HardwareSNTextBox1" />
        <input type="button" value="Test" onclick="javascript:TestOnClosefunction()" />
    </div>
</form>
<script type="text/javascript">
    function TestOnClosefunction() {
        var textBox = document.getElementById('<%= HardwareSNTextBox1.FindControl("AutoCompleteTextBox").ClientID %>');
        console.log(textBox.value);
    }
</script>

To verify it works just click the Test button to print the value of the TextBox in the browser's console.

Explanation

Embedding the line of server-side code and using the ClientID property in JavaScript makes sure your server control will always be discovered no matter what its generated ID is.

UPDATE: Maybe what I should have emphasized is that this line:

var textBox = document.getElementById('<%= HardwareSNTextBox1.FindControl("AutoCompleteTextBox").ClientID %>');

becomes:

var textBox = document.getElementById('HardwareSNTextBox1_AutoCompleteTextBox');

when the page is run. The advantage compared to hard-coding the ID in JavaScript is that it works independent of what value the Control's ClientIDMode property is set to.