Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect the CAPS LOCK state in a password field [duplicate]

Tags:

javascript

Possible Duplicate:
How do you tell if caps lock is on using JavaScript?

In a web form, is there any way to tell if the caps lock is on ?

I suppose I could check do a check onChange to see if all the characters are upper case. But is there a more direct way to do this?

Specifically, I am looking to implement a "YOUR CAPS LOCK IS ON" message when they enter the password field, similar to how the windows login screen does .

like image 971
Byron Whitlock Avatar asked Jan 26 '11 21:01

Byron Whitlock


1 Answers

You can find a decent example of how to do this here: http://www.codeproject.com/KB/scripting/Detect_Caps_Lock.aspx

You could take that code and wrap it into a different kind of event, either, i.e. onfocus or on document load.

You can google for an index of key codes (I'd post a link, but I don't have high enough karma to post more than one link, sorry).

For simplicity the codes you'd be looking for is 20 (Caps lock).


Instructions copied here from site (license: CPOL)

Building the script

<script language="Javascript">
function capLock(e){
 kc = e.keyCode?e.keyCode:e.which;
 sk = e.shiftKey?e.shiftKey:((kc == 16)?true:false);
 if(((kc >= 65 && kc <= 90) && !sk)||((kc >= 97 && kc <= 122) && sk))
  document.getElementById('divMayus').style.visibility = 'visible';
 else
  document.getElementById('divMayus').style.visibility = 'hidden';
}
</script>

Now we have our script ready to go. We now need to associate this script with our form.

Using the script

Let's add two items: a textbox and a DIV. Now we just need to call the onKeyPress event.

<input type="password" name="txtPassword" onkeypress="capLock(event)" />
<div id="divMayus" style="visibility:hidden">Caps Lock is on.</div> 
like image 79
dmcnelis Avatar answered Oct 10 '22 20:10

dmcnelis