[英]Check if text is selected on keydown event
我有一個場景,我阻止用戶輸入十進制后的第二個數字。我有我的代碼在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嗎? 或者還有其他方法嗎?
您可以在按鍵后刪除它,而不是阻止用戶輸入它:
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.