How to "handle" browser autocomplete while typing?

I have an input text username / password, I am using the label I show inside the input, when the input receives focus, the label is hidden when the input is blurred, if the value is not equal to "" the label is shown again, it works fine using focus () functions / blur (), but how can I handle the browser auto-fill because the change () function won't work as focus never gets there, is there a way to handle this?

I dont want to disable autocomplete by disabling it, I think it is not very user friendly.

I thought to use a timer, every nms, but I would like to use a better method.

Any ideas?

Here's 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');
        }
   }
);

      

+2


source to share


2 answers


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

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

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

If you are talking about saved inputs, I believe they will be populated either before or immediately after the page has finished loading, so you can check if the page has loaded (or 1 second after setTimeout

) if the field is empty.



HTML5 has a new placeholder

attribute
, 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') + "'])

      

+1


source


I've done this before and used window.onload

. I would recommend creating two functions that handle the "focus" and "blur" functionality that you can call from multiple 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
    }
}

      

-1


source







All Articles