How do I make a warning when the Caps Lock key is enabled in the password field?
At first I would like solutions in pure JavaScript, but using jQuery and related will be accepted.
How do I make a warning when the Caps Lock key is enabled in the password field?
At first I would like solutions in pure JavaScript, but using jQuery and related will be accepted.
Use getModifierState('CapsLock')
in an event to detect the state. Functional example below:
document.addEventListener('keydown', function( event ) {
var flag = event.getModifierState && event.getModifierState('CapsLock');
console.log( flag ? "Caps Lock ON": "Caps Lock OFF");
});
Clique nesta área e pressione Caps Lock.
All modern browsers (with the exception of Opera Mini) support this method:
The logic behind this is simple: check if the letter you typed is uppercase, and if the shift is not pressed:
document.getElementById('txtSenha').onkeyup = function (e) {
var key = e.charCode || e.keyCode;
//enter, caps lock e backspace não interessam
if(key == 13 || key == 8 || key == 46 || key == 20){
return false;
}
//pega o último caracter digitado
var tamanho = this.value.length
var ultimo_caracter = this.value.substring(tamanho - 1);
//Verifica se é maiúsculo, e se não é shift
if(ultimo_caracter.toUpperCase() == ultimo_caracter
&& ultimo_caracter.toLowerCase() != ultimo_caracter
&& !e.shiftKey)
{
alert('Caps Lock está pressionado!');
}
};
<input type="password" id="txtSenha" />
This example does not use JQuery. You can also customize, allow or block more keys, but I would do something similar to that myself
You can use toUpperCase()
of JavaScript to know if the letter is in uppercase, when the keypress
of Jquery event is called.
$('#example').keypress(function(e) {
var s = String.fromCharCode( e.which );
if ( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey ) {
alert('caps is on');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="password" id="example" />
For more information:
toUpperCase () : link
toLowerCase () : link
Original response in English: link