javascripthtmlasp.netascx

html textbox funtion onkey_Up is not working on ascx control


i tried onkey_up to copy one textbos data to another textbox on an user control ascx file but when i run its not wroking.is it because of i wrote onkey_up function on .ascx , i should write on master page?

function sync() {
        var TextBoxA1 = document.getElementById('TestAmountTextBox');
        var TextBoxA2 = document.getElementById('TestAmountTextBox_2');
        TextBoxA2.value = TextBoxA1.value;
    }

html inpoutbox :

<input type="text" runat="server" id="TestAmountTextBox" class="form-control currency-input" placeholder="From " aria-label="From Transaction Amount" data-allownegative="true" style="width: 100px;" maxlength="14" tabindex="7" onkeyup="sync()"/>                                                         
<input type="text" runat="server" id="TestAmountTextBox_2" class="form-control currency-input" placeholder="To " aria-label="To Transaction Amount" data-allownegative="true" style="width: 100px;" maxlength="14" tabindex="13" />  

Solution

  • By default, adding a textbox to a usercontrol will force ASP.NET to render a unique ID. Something like "usercontrolId_textboxId". You can find the actual ID, by viewing HTML source.

    There are a few options to get around ASP.NET generated IDs:

    Option 1:

    You can turn off ASP.NET autogenerated IDs, by setting ClientIDMode="Static" E.g:

    <input type="text"
          runat="server" 
          id="TestAmountTextBox" 
          ClientIDMode="Static"
          ... [the rest of the attributes]
    

    There are alternative properties in ClientIDMode that can be used. Also it can be turned off completely in web.config.

    If ClientIDMode is set to Static, then ASP.NET will throw an error if the same ID is reused. For example using the usercontrol on more than once on the same page.

    Option 2:

    Bind the ASP.NET ID to the JavaScript code, using ClientID, For example:

    function sync() {
        var TextBoxA1 = document.getElementById('<%= TestAmountTextBox.ClientID %>');
        var TextBoxA2 = document.getElementById('<%= TestAmountTextBox_2.ClientID %>');
        TextBoxA2.value = TextBoxA1.value;
    }
    

    This will only work if the JavaScript is placed on the usercontrol.

    Option 3:

    A third option is to replace getElementById with getElementsByClassName and add another class to the textboxes.