KevinSheedy / jquery.alphanum

Alphanumeric Plugin for jQuery
Other
141 stars 65 forks source link

forceLower/Upper not working #44

Closed nikialeksey closed 6 years ago

nikialeksey commented 9 years ago

Hi! In this code forceLower settings not working:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Test Jquery Alphanum</title>
  </head>
  <body>
    <input type="text" name="name" value="">

    <script src="jquery-1.11.3.js" charset="utf-8"></script>
    <script src="jquery.alphanum.js" charset="utf-8"></script>

    <script type="text/javascript">
      $('input').alphanum({
        forceLower: true
      });
    </script>
  </body>
</html>
nikialeksey commented 9 years ago

Probably, you should change $textbox "keypress" event handler like this:

$textbox.bind("keypress", function(e){

    // Determine which key is pressed.
    // If it's a control key, then allow the event's default action to occur eg backspace, tab
    var charCode = !e.charCode ? e.which : e.charCode;
    if(isControlKey(charCode)
        || e.ctrlKey
        || e.metaKey ) // cmd on MacOS
        return;
    var newChar         = String.fromCharCode(charCode);

    // Determine if some text was selected / highlighted when the key was pressed
    var selectionObject = $textbox.selection();
    var start = selectionObject.start;
    var end   = selectionObject.end;

    var textBeforeKeypress  = $textbox.val();

    // The new char may be inserted:
    //  1) At the start
    //  2) In the middle
    //  3) At the end
    //  4) User highlights some text and then presses a key which would replace the highlighted text
    //
    // Here we build the string that would result after the keypress.
    // If the resulting string is invalid, we cancel the event.
    // Unfortunately, it isn't enough to just check if the new char is valid because some chars
    // are position sensitive eg the decimal point '.'' or the minus sign '-'' are only valid in certain positions.
    var potentialTextAfterKeypress = textBeforeKeypress.substring(0, start) + newChar + textBeforeKeypress.substring(end);
    var validatedText              = trimFunction(potentialTextAfterKeypress, settings);

    // If the keypress would cause the textbox to contain invalid characters, then cancel the keypress event
    if (settings.forceLower && !settings.forceUpper) {
        if (validatedText.toLowerCase() != potentialTextAfterKeypress.toLowerCase()) {
            e.preventDefault();
        }
    } else if(settings.forceUpper && !settings.forceLower) {
        if (validatedText.toUpperCase() != potentialTextAfterKeypress.toUpperCase()) {
            e.preventDefault();
        }
    } else if(validatedText != potentialTextAfterKeypress) {
        e.preventDefault();
    }
});