12
$('#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?

informatik01
  • 16,038
  • 10
  • 74
  • 104
Isis
  • 4,608
  • 12
  • 39
  • 61

3 Answers3

34

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);
});
Brainfeeder
  • 2,604
  • 2
  • 19
  • 37
Amr Elgarhy
  • 66,568
  • 69
  • 184
  • 301
  • 1
    .live tells jQuery that you want this to happen to something whether it was in the original file or was made by javascript. That first part in quotes before the function tells it what kind of event you're looking for (focus in the first instance, blur in the second). Then you define what you want to happen. –  Mar 01 '10 at 12:27
  • 10
    .live is removed as of jQuery 1.9+, use .on instead – Mark Schultheiss Feb 21 '13 at 14:40
2

This for your exact code:

$('#lPass').live('focus', function() {  
    if (this.value == this.defaultValue) this.value = '';
    $(this).after('<input type="password" id="lPass" size="10" value="'+this.value+'"/>').remove();
}).live('blur', function() {
    alert(1);
});
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
2

The first issue I see is that your selector is an ID of #lPass, yet, within that selector you attempt to insert a new tag with that same ID. ID must be unique on the page. THEN you attempt to remove with the .remove() - seems to make no sense to me.

Just use the .remove() or use a new id...

OR clarify what you want to do.

As for the .blur, just use a blur, but the ID must be fixed, or use the .live() as others suggest if you wish to blur the NEW field you added.

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100