Jquery – How to handle elements ID when using jQuery and ASP.NET user controls

asp.netjqueryname-manglingname-matchinguser-controls

I have some user controls in ASP.NET that I am using as simply HTML, that is, without any code-behind.

I one control I have an element with a fixed ID and I am pointing it with some jQuery client scripts. For example:

<div id="slider-section"></div>

<script type="text/javascript" language="javascript">
    $(document).ready(function () {
        var slider = $('#slider-section');
        // ... do something with the jQuery Object
    });
</script>

This works very good without any problem. But there is a side effect with this. In fact, if I add two instances of the same user control on my page I will have two elements with the same ID.

Which is in your opinion a good way to handle a situation like this?

thanks

Best Answer

Asp.net controllers when rendered in client side, creates a different ID, example:

you define a textbox:

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

if you check the source code of the page, you will note that textbox ID will be something like this:

id="{GUID}_Textbox1"

so what you need to do is use a selector to find the end of the ID like this:

<div id="slider-section"></div>

    <script type="text/javascript" language="javascript">
        $(document).ready(function () {      
            var slider = $('input[id$='TextBox1']').{youroptions};
            // ... do something with the jQuery Object
        });
    </script>

check documentation here : http://api.jquery.com/category/selectors/

enjoy ;)