Created
December 6, 2013 04:32
-
-
Save tparton42/7818623 to your computer and use it in GitHub Desktop.
Getting the cursor position of a keypress in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$('alphaonly').keypress(function(e){ | |
// Convert the character code to a string | |
var strIn = String.fromCharCode(e.charCode); | |
// The current cursor position is stored as: e.target.selectionStart | |
if(e.target.selectionStart == 0) { | |
// Setup our pattern, excluding anything other than a-zA-Z | |
var patt = /[a-zA-Z]/gi; | |
} else { | |
// Setup our pattern to allow alpha, spaces and dashes | |
var patt = /[a-zA-Z\s\-]/gi; | |
} | |
// Return the test result | |
return patt.test(strIn); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment