Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery bind focus / blur events to AJAX loaded content

I have this script which works fine to add / remove a class on blur / focus on text inputs and textareas - however I need to bind it to also work on content added after page load via AJAX:

 $(function() {
  $('input[type=text], textarea').addClass("idleField"); // reset all ##
  $('input[type=text], textarea').bind("focus", function(event){
      $(this).removeClass("idleField").addClass("focusField");
      if (this.value == this.defaultValue){ 
       this.value = '';
   }
   if(this.value != this.defaultValue){
       this.select();
      }
  }).bind("blur", function(event){
   $(this).removeClass("focusField").addClass("idleField");
      if ($.trim(this.value) == ''){
       this.value = (this.defaultValue ? this.defaultValue : '');
   }
  });

 });

this is not binding the events to new content - any ideas?

like image 400
Q Studio Avatar asked Jan 26 '11 23:01

Q Studio


People also ask

How to blur an element in jQuery?

Syntax of jQuery Blur Method The jQuery Blur method is called when the control loses its focus. a. To trigger the .blur() event: $(selector).blur() Example: Trigger blur event of an element on button click Here I have a textbox and a button. On the click event of the button the .blur() event of the textbox is triggered and it loses the focus.

How to bind events to Ajax request in jQuery?

The jQuery events (click, change, blur, hover, submit, etc) need to be bind properly in the dynamic content loaded by the Ajax request. You need to use the event delegation for Ajax generated content using jQuery.

What is the focus event in jQuery?

The focus event occurs when an element gets focus (when selected by a mouse click or by "tab-navigating" to it). The focus() method triggers the focus event, or attaches a function to run when a focus event occurs.

Can I use jQuery click like events in the Ajax generated content?

If you use jQuery click like events in the Ajax loaded content, it will not work in a normal scenario. The jQuery events (click, change, blur, hover, submit, etc) need to be bind properly in the dynamic content loaded by the Ajax request. You need to use the event delegation for Ajax generated content using jQuery.


1 Answers

Instead of using .bind, use .on():

$( document ).on( 'focus', 'input[type=text], textarea', function() {
    // stuff here will be applied to present and *future* elements
});
like image 101
karim79 Avatar answered Nov 11 '22 01:11

karim79