Skip to content

Instantly share code, notes, and snippets.

@tparton42
Created December 6, 2013 04:32
Show Gist options
  • Save tparton42/7818623 to your computer and use it in GitHub Desktop.
Save tparton42/7818623 to your computer and use it in GitHub Desktop.
Getting the cursor position of a keypress in JavaScript
$('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