Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

c# - Passing ASP.NET client IDs in to a javascript function

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...