How to "handle" the browser autocomplete on input text?
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 i开发者_StackOverflow中文版f 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');
}
}
);
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') + "'])
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
}
}
精彩评论