views:

253

answers:

2

Hi,

I have an input text login/password, i use a label which i display inside the input, when the input takes the focus, the label is hidden, when the input it is blurred if the value is not equal to "" the label is displayed again, it works great using the focus() / blur() functions, but, how could i handle the browser auto filling, because the change() function won't work, since the focus is never gained, is there a way to handle this ?

I don't want to disable autocomplete by setting it to off, i think, it is not really user friendly to this.

I thought to use a timer, every n ms but i would have like to use a better method.

Any ideas ?

Here is my script :

$('#form-login input.inputbox').focus(
   function()
   {
        $('#label-' + $(this).attr('id')).addClass('hidden');
   }
);

$('#form-login input.inputbox').blur(
   function()
   {
        if ($(this).val() == "")
        {
         $('#label-' + $(this).attr('id')).removeClass('hidden');
        }
   }
);
+1  A: 

There are several jQuery plugins that already do this; I recommend this one.

To answer your question (if you really want to reinvent the wheel), are you talking about autocomplete or saved logins?

If you're talking about autocomplete, it will only happen when the field is focused (AFAIK), so you don't need to worry.

If you're talking about saved logins, I believe that they will be filled in either before or just after the page finishes loading, so you can check on page load (or 1 second later with setTimeout) whether the field is empty.

HTML5 has a new placeholder attribute to do this, but browsers don't support it yet.


By the way, instead of giving each label an ID, you can use the following selector:

$('label[for='" + $(this).attr('id') + "'])
SLaks
I'm talking of the browser autocomplete yes, saved logins for example.I'll take a look to this plugin.
Boris Guéry
For your suggestions about saved login, the problems is still relevant if there are several saved logins, because none is loaded by default, but loaded with "autocomplete like" when tape the first letter
Boris Guéry
Btw the correct link of the plugin is : http://fuelyourcoding.com/scripts/infield/
Boris Guéry
(a lot of comments !) well i tested the plugin, but it uses "autocomplete=off" to prevent saved login, which i don't to disable for my user.
Boris Guéry
thanks for the label's tip !
Boris Guéry
A: 

I did this before and used window.onload. I'd recommend creating two functions that handle the 'focus' and 'blur' functionality, which you can call from several places.

function inputFocus( elem )
{
    // hide the label
}

function inputBlur( elem )
{
    // show the label
}

window.onload = function()
{
    // get username/password values first

    if ( username.length > 0 ) {
        // call inputFocus with jQuery object
    }            
    if ( password.length > 0 ) {
        // call inputFocus with jQuery object
    }
}
DisgruntledGoat