检查是否在keydown事件上选择了文本

时间:2016-10-24 08:42:38

标签: javascript jquery angularjs

我有一个场景,我阻止用户在小数点后输入第二个数字。我在keydown事件上有我的代码。 以下是我的代码:

$scope.Inputkeydown = function (event, value) {        
    if (event.keyCode != 8) {
        if (value != null && value != undefined && value != "") {
            var regex = /^\d*\.\d$/;  //this regex passes only decimal numbers with one digit after decimal
            if (regex.test(value)) {                   
                    event.preventDefault();
            }
        }
    }

};     

现在麻烦的是,如果用户选择文本框中的文本(例如50.0)并且说当时按下5它也会被阻止,因为文本框值是50.0并且正则表达式允许它去并且它被阻止从键入。

我可以检查keydown是否正在复制文本?或者还有其他方法吗?

1 个答案:

答案 0 :(得分:0)

您可以在按下后删除它,而不是阻止用户输入它:

function filterDecimals(inp) {
    return inp.replace(/^(\d*\.\d)\d*$/g, '$1');
}

或者,如果您要删除其后的所有内容,请将第二个\d*替换为.*

编辑(使用示例)

此函数将文本作为输入并返回新的过滤文本。要使用它,只需在keypress上附加一个事件处理程序,如下所示:

<input type="text" id="filteredbox">

<script>
var txt = document.getElementById("filteredbox");

// on keyup event (you can change to keypress if you want, but this is more logical here
txt.addEventListener("keyup", function(){
    // sets value of txt to the returned data from filterDecimals()
    // if statement: only filters it if necessary; this eliminates the "selected text" issue you mentioned
    if (this.value !== filterDecimals(this.value)) {
        this.value = filterDecimals(this.value);
    }
});
</script>
相关问题