2

I have several dynamically loaded text areas which don't seem to respond when they get blurred. I load them using .post (they get generated in a php script and returned as data for display). I made this jsfiddle, which works by itself, but not on my page. Could the problem be that the textareas are dynamically loaded? I read elsewhere on SO that I should use .on() for dynamically loaded elements (and I did use it), but it still doesn't work on my page. This is the jQuery code in the jsfiddle:

$('.crit_desc').on('blur', function () {

    var value = $(this).val();
    alert(value);

});
Veris
  • 35
  • 1
  • 1
  • 6

2 Answers2

5

Change your code to this:

$(document).on('blur', '.crit_desc', function () {
    var value = $(this).val();
    alert(value);
});

Since your elements are loaded dynamically, they need to be bound to an element that exists in the DOM when the page loads. Ideally you want an element closer to your dynamically loaded element than document to help performance.

Per the docs on .on():

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.

j08691
  • 204,283
  • 31
  • 260
  • 272
  • That works! Can you explain why this works, but what I previously had doesn't? Just in case something similar happens again. – Veris Feb 24 '13 at 18:07
  • 1
    As I mentioned in my answer, when you bind events to dynamically loaded elements, you have to use `.on()` in a slightly different way. See my answer's explanation and the documentation for `.on()`. Oh, and if my answer helped you, please consider upvoting it and/or marking it as the accepted answer. – j08691 Feb 24 '13 at 18:08
  • Ok, thanks! It's just that when I first saw your answer, the explanation didn't show for some reason. I'll accept the answer after the required minutes. – Veris Feb 24 '13 at 18:11
  • Not sure if this should be another question, but is there a way to change the html – Veris Feb 24 '13 at 18:29
0

If it's loaded dynamically use livequery http://docs.jquery.com/Plugins/livequery

$('.crit_desc').livequery('blur', function () {
    var value = $(this).val();
    alert(value);
});

Or check this Simulating "focus" and "blur" in jQuery .live() method because .live doesn't support blur and focus

Community
  • 1
  • 1
Antonio Papa
  • 1,596
  • 3
  • 20
  • 38