0

Okay, I've managed to get .on working on a different site, but for some reason it is just being a pain in this one.

here is my code:

$("#tabSection").on("click", "a.tab", function () {
    alert('bob');
});

and the HTML (which will be loaded via jQuery .load():

<div id="tabSection">
    <table border=0 width="750px" cellspacing=0 cellpadding=0>
    <tr><td class="tab"><a href="javascript:void();" rel="details" class="tab selected">Details</a></td>

Obviously I close the table and the tabsection div. It was all working fine before I got it loading via ajax. Now, i cant get it work at all. Any suggestions as to why it wouldnt be? Am i missing something here?

4
  • How are you loading it via AJAX? Commented Jun 30, 2012 at 1:51
  • like this: $("#customerForm").html(loading).load(filename); Commented Jun 30, 2012 at 1:52
  • #customerForm does not appear in your sample code. If it is a parent of #tabSection, then #tabSection probably didn't exist in the document when you ran the shown JS. Commented Jun 30, 2012 at 1:54
  • This is actually covered, with a bold warning, in the fine manual: "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()" Commented Jun 30, 2012 at 1:54

1 Answer 1

8

You are loading the #tabSection element, which means that it doesn't exist when you try to hook up the event.

The element that you hook up the event to have to exist when you hook it up. Use the element where you load the HTML.

$("#customerForm").on("click", "#tabSection a.tab", function () {
  alert('bob');
});
Sign up to request clarification or add additional context in comments.

3 Comments

Perfect. Quick and easy. I changed "#tabSection" to "#customerForm" and it works beautifully. Thank you.
Small comment: it's convention to use single quotes with JS and double quotes with html. i.e. $('#customerForm').on('click', '#tabSection a.tab'...
@Archonic: That is one convention of many different, and one that I usually use myself. However, in this case I chose to use the same convention as the OP uses, to make the code in the answer easier to compare to the code in the question.

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.