I need to pass a client ID to a Javascript function in the onblur event of an ASP.net control event like this:
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 gets passed in literally as '<%= txtClientName.ClientID %>' instead of the actual value. So, calling document.getElementById(controlID); doesn't work.
How can I get the actual client ID and pass it to my Javascript function?
You could either change the asp.net control to standard html element (i.e., without runat="server")
or see this Stack Overflow answer:
problem assigning declarative values in asp:hyperlink. error: this is not scriptlet. will output as plain text
or use jquery
pass this object from the function and can get this.id from javascript that will be
ClientID
Is this from the code-behind?
How about
OnBlur=String.Format("javascript:setBackground(this, '{0}')", txtClientName.ClientID);