我有一個input
元素與numbersOnly
類只允許寫(鍵盤)這個數字格式 - >#,##
例如。 2,04
或39,14
輸入只用於浮點值
另外,當2位被逗號之前是不允許的第一個數字爲。
我正在測試這個代碼 - 但我仍然沒有運氣。
$('.numbersOnly').keyup(function() {
this.value = this.value.replace(/^[0-9]*[,][0-9]+$/,'');
});
我有一個input
元素與numbersOnly
類只允許寫(鍵盤)這個數字格式 - >#,##
例如。 2,04
或39,14
輸入只用於浮點值
另外,當2位被逗號之前是不允許的第一個數字爲。
我正在測試這個代碼 - 但我仍然沒有運氣。
$('.numbersOnly').keyup(function() {
this.value = this.value.replace(/^[0-9]*[,][0-9]+$/,'');
});
可能是一個更簡單的方法,但這似乎工作。 Jsfiddle:http://jsfiddle.net/8GU6e/4/
這確實假定任何數字的數字是有效的,我並不完全清楚你想要的。是「12,12345」有效嗎?這是假設的。經過Chrome和Firefox測試。
$('.numbersOnly').keypress(function (e) {
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
// Firefox will trigger this even on nonprintabel chars... allow them.
switch (charCode) {
case 8: // Backspace
case 0: // Arrow keys, delete, etc
return true;
default:
}
var lastChar = String.fromCharCode(charCode);
// Reject anything not numbers or a comma
if (!lastChar.match("[0-9]|,")) {return false;}
// Reject comma if 1st character or if we already have one
if (lastChar == "," && this.value.length == 0) {return false;}
if (lastChar == "," && this.value.indexOf(",") != -1) {return false;}
// Cut off first char if 0 and we have a comma somewhere
if (this.value.indexOf(",") != -1 && this.value[0] == "0") {
this.value = this.value.substr(1);
}
return true;
});
sames不能工作 - 輸入不接受鍵盤輸入 – Mike
似乎只能在Chrome上工作。人力資源管理。 – PherricOxide
已更新爲適用於Chrome和Firefox的版本。 – PherricOxide
當一個無效的鍵進來時,應該可能會返回false,而不是試圖使其爲空。無需手動進行分配,只需過濾按鍵。 – Orbling
那麼「2,23」是一個有效的字符串?或者它必須是2位數字?當用戶輸入「02,33」時你想要發生什麼? – PherricOxide
@PherricOxide用戶不能寫入「02,33」 - >它應該改爲「2,33」 - 但是數字應該是「2,04」,在「4」之前應該有「0」 「 – Mike