3

I have this code for adding a keypress to a password. If capslock is on it will trigger. I got it from How do you tell if caps lock is on using JavaScript?

$("input[type='password']").keypress(function(e) {

    var $warn = $(this).next(".capsWarn"); // handle the warning mssg
    var kc = e.which; //get keycode
    var isUp = (kc >= 65 && kc <= 90) ? true : false; // uppercase
    var isLow = (kc >= 97 && kc <= 122) ? true : false; // lowercase
    // event.shiftKey does not seem to be normalized by jQuery(?) for IE8-
    var isShift = ( e.shiftKey ) ? e.shiftKey : ( (kc == 16) ? true : false ); // shift is pressed

    // uppercase w/out shift or lowercase with shift == caps lock
    if ( (isUp && !isShift) || (isLow && isShift) ) {
        $warn.show();
    } else {
        $warn.hide();
    }

}).after(capLock());
function capLock(e){
 alert('CAPSLOCK is ON');
}

The original code has the message in a span:

...}).after(<span class='capsWarn error' style='display:none;'>CAPSLOCK is ON</span>);

I wanted it to be an alert message but it is not performing as I expect it to. On load it should alert the message but even if the capslock is on it is not showing the alert.

How do I get it to detect the key and present the alert?

Community
  • 1
  • 1
guradio
  • 15,524
  • 4
  • 36
  • 57

1 Answers1

6
$("input[type='password']").keypress(function(e) {

    var $warn = $(this).next(".capsWarn");//can be removed since you are just using alert
    var kc = e.which; //get keycode
    var isUp = (kc >= 65 && kc <= 90) ? true : false; // uppercase
    var isLow = (kc >= 97 && kc <= 122) ? true : false; // lowercase
    // event.shiftKey does not seem to be normalized by jQuery(?) for IE8-
    var isShift = ( e.shiftKey ) ? e.shiftKey : ( (kc == 16) ? true : false ); // shift is pressed

    // uppercase w/out shift or lowercase with shift == caps lock
    if ( (isUp && !isShift) || (isLow && isShift) ) {
        capLock(); // alerts "CAPSLOCK is ON"
    }

});
function capLock() {
 alert('CAPSLOCK is ON');
}
chris97ong
  • 6,870
  • 7
  • 32
  • 52
  • 7
    Please [edit] with more information to explain how this addressed the problem. Code-only answers are [discouraged](//meta.stackexchange.com/questions/196187), because they contain no searchable content, and don't enhance readers' understanding. – Mogsdad Sep 30 '15 at 17:31