jQuery onblur not working

Isis picture Isis · Mar 1, 2010 · Viewed 64.5k times · Source
$('#lPass').focus(function() {  
        if (this.value == this.defaultValue) this.value = '';
        $(this).after('<input type="password" id="lPass" size="10" value="'+this.value+'"/>').remove();
}).blur(function() {
    alert(1);
});

<input id="lPass" type="text" size="10" value="Password"/>


onblur not working.
Any ideas?

Answer

Amr Elgarhy picture Amr Elgarhy · Mar 1, 2010

Use live instead of focus and blur

.live() has been deprecated. Use .on() and .off() instead.

because you are adding the input in run time, so it adds to the page with out the events, live:

Attach a handler to the event for all elements which match the current selector, now or in the future.

Example:

$('#lPass').on('focus', function() {
    if (this.value == this.defaultValue) this.value = '';
    $(this).after('<input type="password" id="lPass" size="10" value="' + this.value + '"/>').remove();
});


$('#lPass').on('blur', function() {
    alert(1);
});