1

I'm having an issue using JQuery within an ASP.NET website. I want to bind a common click handler to multiple similar elements (generated through a ListView for those familiar with ASP.NET). My assumption was to use a class selector as follows (as an example):

$('.standard-group').click(function () {
    alert($(this).attr("id"));
});

This relates back to a series of divs having this class:

<div class="standard-group">
    some content
</div>

<div class="standard-group">
    some other content
</div>

Furthermore, the content is generated inside a ContentPlaceholder and merged into a master page (2 nested master pages actually). I've tried putting the click handler between <script></script> tags inside a second ContentPlaceholder that injects it's content into the <head> section of the page, tried putting it with the content in the main ContentPlaceholder all to no avail. What ends up happening is that the generated page loads correctly and I can inspect the source and see the function there, but no event is raised. I suspect it's something to do with the master page/server processing scenario, but can't pinpoint it.

Any help out there?

1
  • Can you show some sample pages (view source from your favorite browser) Commented Apr 5, 2013 at 6:14

2 Answers 2

1

Your script for adding event could be executing before the element being created, you can use on() to delegate event to document.

$(document).on('click', '.standard-group', function () {
    alert($(this).attr("id"));
});

delegated events

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next. Reference

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, thanks for the answer and the explanation of why. It now works, but only when I put the function inside the MainContentPlaceholder, and not HeadContentPlaceholder. I guess I don't know enough about the ASP.NET page life-cycle and what order stuff gets executed in.
1

delegate the click event to document with on()

 $(document).on('click','.standard-group',function () {
    alert($(this).attr("id"));
});

link to read more about on()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.