Many other solutions using keystrokes will not work on mobile devices, you need to use input .
HTML
<input type="text" id="name" data-value="" autocomplete="off" spellcheck="true" placeholder="Type your name" autofocus />
JQuery
$('#name').on('input', function() { var cursor_pos = $(this).getCursorPosition() if(!(/^[a-zA-Z ']*$/.test($(this).val())) ) { $(this).val($(this).attr('data-value')) $(this).setCursorPosition(cursor_pos - 1) return } $(this).attr('data-value', $(this).val()) }) $.fn.getCursorPosition = function() { if(this.length == 0) return -1 return $(this).getSelectionStart() } $.fn.setCursorPosition = function(position) { if(this.lengh == 0) return this return $(this).setSelection(position, position) } $.fn.getSelectionStart = function(){ if(this.lengh == 0) return -1 input = this[0] var pos = input.value.length if (input.createTextRange) { var r = document.selection.createRange().duplicate() r.moveEnd('character', input.value.length) if (r.text == '') pos = input.value.length pos = input.value.lastIndexOf(r.text) } else if(typeof(input.selectionStart)!="undefined") pos = input.selectionStart return pos } $.fn.setSelection = function(selectionStart, selectionEnd) { if(this.lengh == 0) return this input = this[0] if(input.createTextRange) { var range = input.createTextRange() range.collapse(true) range.moveEnd('character', selectionEnd) range.moveStart('character', selectionStart) range.select() } else if (input.setSelectionRange) { input.focus() input.setSelectionRange(selectionStart, selectionEnd) } return this }
source share