4

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?

Gagege
  • 650
  • 3
  • 8
  • 20

3 Answers3

7

You could either change the asp.net control to standard html element (i.e., without runat="server")

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

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

<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>
Community
  • 1
  • 1
Jason
  • 4,897
  • 2
  • 33
  • 40
  • For the first answer, I don't really have that option. I need to get at these controls from the code behind. Also, using the "<%# %>" gives me the exact same result. – Gagege Jun 14 '11 at 15:08
  • Understood. And then does the <%# ... %> syntax do it for you? – Jason Jun 14 '11 at 15:10
  • @Gagege no worries... jquery an option? (Added to answer) – Jason Jun 14 '11 at 15:25
  • Incidentally, if you use jquery, you could probably replace the setBackground function with something a little more concise. – Jason Jun 14 '11 at 15:28
  • Once again, jQuery to the rescue. :) Thanks! – Gagege Jun 14 '11 at 15:36
1
<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 the function and can get this.id from javascript that will be ClientID

Tala
  • 8,888
  • 5
  • 34
  • 38
nadeem
  • 11
  • 1
1

Is this from the code-behind?

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

George Duckett
  • 31,770
  • 9
  • 95
  • 162