Search code examples
javascriptprototypejs

Javascript prevent autocomplete


I recently started with Javascript, and I have found one issue with my password.length check.
http://jsfiddle.net/uYss7/ Code:

document.observe('dom:loaded', function() {
    $('passwordan').observe('keypress', function(event) {
        if (this.value.length < 5) {    
            this.setStyle({backgroundColor: 'blue'});

        } else {
            this.setStyle({backgroundColor: 'white'});
        }
    });
});     

Issue:
It automatically fills it with information. I'm on 127.0.0.1, the reason the box is "passwordan" is simply because I wanted to see if Firefox remembers previously entered data after box names or id, but that doesn't seem to be the case.
What happens is that it automatically fills in five *, and this breaks my Javascript. Its length is 5, and if I click inside the box, ctrl + a (marks the five *), and write a letter(without backspace, just replacing), it's still white. It's length is now 1, and it's supposed to be blue (since length is less than 5). If I mark it, click backspace and write a letter, then it works as supposed.
Here's an image that explains:
http://makeagif.com/media/2-02-2013/pc1TSL.gif

*

pktangyue gave me the fix:

A simple way to fix it is using keyup event instead of keypress.

Because keypress triggered before value change, while keyup triggered after it.

Thanks!
*And one more question, why is there a gray border on top after going to blue (and to white again)?


Solution

  • A simple way to fix it is using keyup event instead of keypress.

    Because keypress triggered before value change, while keyup triggered after it.