开发者

Login textfield and password fields remove text on focus

I'm developing the login section on my website and want it to use the same effect such as twitter has with the removal of the Username and Password values when the Textfield and Password field is on focus. I've tried using plain javascript for this with something of the following lines...

function PasswordClick(evt) {

    if ("Password" === this.value) this.value = "";
if(this.getAttribute('type')=='text')
        {
                this.setAttribute('type','password');
        }
        this.focus();
}
开发者_JAVA技巧

It seems to cause problems using Chrome 12.0.742.100 on Windows and prob other web-kit browsers but works fine on Firefox.

Has anyone got a better way of doing this?

Thanks in advance.


You could also use the placeholder attribute, compatible with all modern browsers, along with a JQuery placeholder script that adds the same functionality to older browsers.

The answers to this SO question might be helpful, and also contain a link to a great but simple placeholder script:

https://stackoverflow.com/questions/5120257/what-is-the-best-html5-placeholder-like-jquery-plugin-out-there

https://github.com/marcgg/Simple-Placeholder


Your corrected code version:

function PasswordClick(evt) {

    if ("Password" === $(this).val()){$(this).val('');}
    if($(this).attr('type')=='text'){
       $(this).attr({'type':'password'});
    }
        $(this).focus(function(){PasswordClick(evt);});
}

Please, read some jQuery documentation before start programming with it.


This code should do what you want. This part should go in the HEAD section of your page:

function init() {
    document.getElementById('password').type = 'text';
}
window.onload = init;

function gotFocus(item) {
    if (item.value == 'Password') {
        item.value = '';
        item.type = 'password';
        item.style.color = '';
    }
}

function lostFocus(item) {
    if(item.value == '') {
        item.value = 'Password';
        item.type = 'text';
        item.style.color = '#C0C0C0';
    }
}

And then where you want the password input to be, you would put this HTML:

<input id='password' name='password' type='password' onfocus="gotFocus(this);" onblur="lostFocus(this);" value="Password" style="color:#C0C0C0" />


There are many solutions, however, the one I find the easiest and, and looks the best is this jQuery plugin: http://fuelyourcoding.com/scripts/infield/

It adds some very nice effects also.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜