Search code examples
jqueryinputcursor-position

Input text field filtering using jquery causes cursor to jump in IE and Chrome


I am filtering input in input text fields, for example:

And I am filtering input on the fly, like removing non-numeric characters.

$("#txtlevel").bind('keyup', function(evt)
{
    var value = $(this).val();
    value = value.replace(/\D/g, '');   /* Remove any non-digit characters */
    if ( value.length > 1 )
    {
        value = value.replace(/^[ 0]/g,'');   /* Remove any leading spaces or zeros */
    }
    $(this).val(value);
}

This works great in Firefox, but in IE and Chrome the cursor jumps to the end of the input field every time. How can I prevent this or reset the cursor position? I've seen code to do it for textfields but not input text fields.


Solution

  • When you use keyup and do regex replace (in other words, setting the value), the cursor will jump to the end. If your goal is to allow only numeric keys (plus backspace, delete), try this:

    $("#txtlevel").bind('keydown', function(event) {
        // Allow only backspace, delete, left and right arrows, return and tab
        if (event.keyCode == 46 || 
            event.keyCode == 8 || 
            event.keyCode == 37 || 
            event.keyCode == 39 || 
            event.keyCode == 13 || 
            event.keyCode == 9) {
            // let it happen
        }
        else {
            // stop the keypress if not a number
            if (event.keyCode < 48 || event.keyCode > 57 ) {
                event.preventDefault(); 
            }   
        }
    });
    

    To cancel out non-numeric events on paste, bind it to paste event:

    $("#txtlevel").bind('paste', function(e){ 
        var value = $(this).val();
        value = value.replace(/\D/g, '');   /* Remove any non-digit characters */
        if ( value.length > 1 ) {
            value = value.replace(/^[ 0]/g,'');   /* Remove any leading spaces or zeros */
        }
        $(this).val(value);
    });