can't select text after making input only numeric

This problem seems to happen in webkit based browsers (chrome and safari). Not Firefox.

After constraining certain input fields to only numerics and a : I'm no longer able to select the text or move the cursor to the left with the arrow keys. The input gets deselected or in case of the cursor: it's moved to the end of the input. (I am able to place the cursor somewhere in the string by clicking there with my mouse)

Code used:

$('#from, #to, #rate, #break').keyup(function () { 
    this.value = this.value.replace(/[^0-9:.]/g,'');
});

Example in a fiddle: http://jsfiddle.net/PaulvdDool/EKYBr/

Did I do something wrong? Is it a negative side effect I can't do anything about? Or is there a way to make textselection and cursor movement possible?


When you overwrite the value, the caret automatically goes the end of the input.

What you need to do is overwrite the value, only if needed. ie something like:

$('#from, #to, #rate, #break').keyup(function () { 
    switch(e.which) {
        case 37:
        case 38:     
        case 39:
        case 40: break;
        default: this.value = this.value.replace(/[^0-9:.]/g,'');
    }
});

Demo


Your overwrite the value everytime. you better should get the key and don't let the user input it.

$('#time').keydown(function (event) {
        // 48-56 => 0-9 | 58 = ":"
        if((event.keyCode < 48 || event.keyCode > 56) or event.keyCode != 58)
        {
            event.preventDefault();
        }
});

Check this fiddle

链接地址: http://www.djcxy.com/p/68452.html

上一篇: 无法在键入选择之后更改输入值

下一篇: 输入数字后才能选择文本