Passing ASP.NET client identifiers to javascript function

I need to pass the client ID of the Javascript function in the onblur event of the ASP.net control event as follows:

OnBlur="javascript:setBackground(this, '<%= txtClientName.ClientID %>')" 

Here is my Javascript function:

 function setBackground(sender, controlID) { sender.style.backgroundColor = "#ffffff"; var nextElement = document.getElementById(controlID); if ((nextElement.value == '' || nextElement.value == 'Select') && tab == true) { nextElement.style.backgroundColor = "#f7C059" tab = false; } } 

The problem is that the client ID is passed literally as "<% = txtClientName.ClientID%>" instead of the actual value. So, calling document.getElementById (controlID); does not work.

How can I get the actual client id and pass it to my Javascript function?

+4
source share
3 answers

You can either change the asp.net control to a standard html element (ie without runat = "server")

 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <input type="text" id="ClientText1" onblur="javascript:alert('<%= TextBox1.ClientID %>')" /> 

or see this answer:

problem with assigning declarative values ​​in asp: hyperlink. Error: this is not a scriptlet. will be displayed as plain text

or use jquery

 <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"> </script> <script type="text/javascript"> $(document).ready(function () { $("#text2").blur(function(){alert('<%= TextBox1.ClientID %>')}); }); </script> 
+7
source

Is this from code?

How about OnBlur=String.Format("javascript:setBackground(this, '{0}')", txtClientName.ClientID);

+1
source
 <asp:TextBox ID="TextBox1" runat="server" onclick="dosomething(this)"></asp:TextBox> <script> function dosomething(obj) { var txtObj= document.getElementById(obj.id); alert (txtObj); } </script> 

pass this object from function and can get this.id from javascript which will be ClientID

+1
source

All Articles