Most problems can be prevented by simply updating the input value only if it really changes.
$( '#sample' ).on( 'keyup', function( event ) { var str = $( this ).val(); str = str.replace(/[^A-Za-z-0-9.'\s]/g, "").substring(0,15); if($( this ).val() != str) { $( this ).val( str ); } });
To allow the removal of characters from the middle of the text, you must remember and reset the position of the carriage. To do this, you can use the following functions:
$.fn.getCaretPosition = function() { var el = $(this).get(0); var pos = 0; if ('selectionStart' in el) { pos = el.selectionStart - 1; } else if ('selection' in document) { el.focus(); var Sel = document.selection.createRange(); var SelLength = document.selection.createRange().text.length; Sel.moveStart('character', -el.value.length); pos = Sel.text.length - SelLength; } return pos; } $.fn.setCaretPosition = function(pos) { if ($(this).get(0).setSelectionRange) { $(this).get(0).setSelectionRange(pos, pos); } else if ($(this).get(0).createTextRange) { var range = $(this).get(0).createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } }
And expand your keyboard handler:
$('#sample').on('keyup', function(event) { var str = $(this).val(); str = str.replace(/[^A-Za-z-0-9.'\s]/g, "").substring(0, 15); if ($(this).val() != str) { var pos = $(this).getCaretPosition(); $(this).val(str); $(this).setCaretPosition(pos); } });
See the updated FIDDLE .
source share