Not getting ClientID in ASP.Net

63,580

Solution 1

There are a few solutions to this problem.

One of the simpler would be to move the name into a JavaScript variable since the problem only occurs within the control when trying to evaluate txt_name.ClientID inside the OnClientClick attribute of an ASP.NET control.

<script>
var txtName = '<%= txt_name.ClientID %>';
</script>

Enter server name: <asp:TextBox ID="txt_name" runat="server"></asp:TextBox>
 <asp:Button ID="btn_view" runat="server" OnClick="View_btn_click" 
OnClientClick="return  AlertOnGo('View Configuration', 
document.getElementById(txtName).value)" Text ="GO!" />

Solution 2

you can use the property ClientIDMode="Static" inside the asp:textbox tag

like this

<asp:TextBox ClientIDMode="Static" ID="txt_name" runat="server"></asp:TextBox>
<asp:Button ID="btn_view" runat="server" OnClick="View_btn_click" 
 OnClientClick="return  AlertOnGo('View Configuration', 
 document.getElementById(txtName).value)" Text ="GO!" />

this way the client id of the text box would be same as the "id" and you can use document.getElementById('txt_name').value

and it works for me

Share:
63,580
Abhay Kumar
Author by

Abhay Kumar

Updated on July 09, 2022

Comments

  • Abhay Kumar
    Abhay Kumar almost 2 years

    I have ASP.Net page where i am calling a JavaScript function like this:

     Enter server name: <asp:TextBox ID="txt_name" runat="server"></asp:TextBox>
     <asp:Button ID="btn_view" runat="server" OnClick="View_btn_click" OnClientClick="return  AlertOnGo('View Configuration',document.getElementById('<%= txt_name.ClientID %>').value)" Text ="GO!" />
    

    But on clicking the GO button, i am getting the following error:

    JavaScript runtime error: Unable to get property 'value' of undefined or null reference

    On viewing the rendered code for the button:

    <input type="submit" name="btn_view" value="GO!" onclick="return AlertOnGo('View Configuration',document.getElementById('<%= txt_name.ClientID %>').value);" id="btn_view" />
    

    It is not putting the appropriate ClientID. I tried setting the CLientIDMode to static for the test box, yet no help.

    This question is similar to this unanswered question.