我不希望允許在文本框中輸入並複製和粘貼十進制值和字母。而且我可以輸入負值。但負面符號(「 - 」)應始終在開始。請看下面的小提琴。在這個小提琴中它不允許小數值和字母表。但是,如果我像這樣複製並粘貼「22.50」,它將採用十進制值。我如何限制這一點。不允許複製和粘貼文本框中的小數和文本值
我的要求,
1)只允許數字(正數和負數)。
2)「 - 」符號應該在開頭。不允許在中間或某處。
3)字母不應該允許甚至複製粘貼也。
4)我可以複製粘貼數字,如「2222」和「-2222」。但不是字符和小數。
var input = document.getElementById("myInput");
input.onkeypress = function(e) { e = e || window.event;
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
// Allow non-printable keys
if (!charCode || charCode == 8 /* Backspace */) {
return;
}
var typedChar = String.fromCharCode(charCode);
// Allow numeric characters
if (/\d/.test(typedChar)) {
return;
}
// Allow the minus sign (-) if the user enters it first
if (typedChar == "-" && this.value == "") {
return;
}
// In all other cases, suppress the event
return false;
};
<input type="text" maxlength="10" id="myInput">
請幫我這樣做。
怎麼樣? –
您的輸入是表單的一部分嗎?你可以在提交表單時使用'pattern'驗證嗎? – jritchey
在input.onkeypress函數內部添加一條警報聲明。然後你會看到這個函數是在過濾輸入。它可能不會被粘貼輸入執行。 – JohnH