Roobah
Roobah

Reputation: 321

Jquery is not working with usercontrol

I have a button inside a usercontrol . The usercontrol is loaded (added) to a placeholder by some event . The problem is a simple jquery click event for this button is not working . What am I missing ? What should the selector look like ?

$('#mybutton').click(function () { alert("..."); }); 

Or I have to traverse to it ?

note: I managed to get the usercontrol codebehind executed .

Thanks a lot .

Upvotes: 2

Views: 5474

Answers (4)

Dimitri
Dimitri

Reputation: 7013

Try this:

$('#mybutton').live("click", function () { alert("..."); }); 

Since the control #mybutton is added to the page AFTER $(document).ready() fires, there's no way jQuery can add the handler to that object. The live means, no matter when and how an element is created, it's "click" event will be bound to the function provided as the second argument.

BTW. #mybutton assumes that either the element is standard html object or an ASP control that after render retains ID and NAME as mybutton. If it's not, replace $("#mybutton") with $("#<%= mybutton.ClientID %>") or try setting ASP control's ClientIDMode to Static, or accessing the control by class name.

EDIT:

Going forward suggested method of appending event handlers is

$('#mybutton').on("click", function () { alert("..."); }); 

Upvotes: 4

Francis Musignac
Francis Musignac

Reputation: 331

I have had similar problems and found this solution: placed the link to the jquery file and an empty script tag on the page using the control like this (inside of the header tag):

<script type="text/javascript" src="../scripts/jquery-1.10.1.min.js" />
<script type="text/javascript" language="javascript"></script>

And then on the user control itself (no header tag):

<script type="text/javascript" language="javascript">
$(document).ready(function() {
    //your function here.
});
</script>

Hope this helps!

Upvotes: 1

Basant B. Pandey
Basant B. Pandey

Reputation: 345

In aspx Page when you place the button inside the place holder. the Client ID automatically changed. So you have to use the Jquery End with selector. http://api.jquery.com/attribute-ends-with-selector/

you use the $ sign use to find the dynamic control ID.

$("input[id$=mybutton]").click(function () { alert("..."); }); 

Upvotes: 0

neeebzz
neeebzz

Reputation: 11538

You need to check at client side that the id is the same as mybutton ? ASP.NET replaces the Client ID of all user controls with the attributes runat="server" .

You can view the source code to see the modified id.

Upvotes: 0

Related Questions