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?
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.
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.
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.
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.
Instead of using .bind
, use .on()
:
$( document ).on( 'focus', 'input[type=text], textarea', function() {
// stuff here will be applied to present and *future* elements
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With