1

When I retrieve html with $.get(), the html contains form fields like input, textarea, etc. I want the change, paste and keypress events to be attached to those controls but these events are not getting fired. The jQuery docs state that at least one of those controls needs to be present in the html BEFORE retrieving the html with $.get(). Alternatively you could use the document element which doesn't require any controls present in advance but this has major performance issues, so I will place a hidden control on the page before ajax is called. Here is my html:

<div id="divAdminContent">
  <form id="frmAdmin">
    <input type="text" style="display:none" />
  </form>
</div>

and here is how I am attaching "on":

$("#frmAdmin :input").on("change paste keypress", function (e)
{
  // Do something...
});

1 Answer 1

5

You need event delegation using on() the time your event binding code executes the element you are trying to bind event is not present.

$("#frmAdmin").on("change paste keypress", ":input", function (e)
{
  // Do something...
});

Delegated events

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers, jQuery doc

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

3 Comments

I actually read about delegation but clearly didn't understand how the 2nd selector was to be used. Thanks. It works now.
It is also interesting to note that contrary to what the jQuery docs state, you are NOT required to have a control present in the html prior to calling $.get(). I removed the <input> element and it worked without it.
If you use event delegation you do not need the element on which you want to bind the event rather you need its static parent or document.

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.