2013-10-16 37 views
3

我有一個input元素與numbersOnly類只允許寫(鍵盤)這個數字格式 - >#,##例如。 2,0439,14輸入只用於浮點值

另外,當2位被逗號之前是不允許的第一個數字爲。

我正在測試這個代碼 - 但我仍然沒有運氣。

$('.numbersOnly').keyup(function() { 
    this.value = this.value.replace(/^[0-9]*[,][0-9]+$/,''); 
}); 
+1

當一個無效的鍵進來時,應該可能會返回false,而不是試圖使其爲空。無需手動進行分配,只需過濾按鍵。 – Orbling

+0

那麼「2,23」是一個有效的字符串?或者它必須是2位數字?當用戶輸入「02,33」時你想要發生什麼? – PherricOxide

+0

@PherricOxide用戶不能寫入「02,33」 - >它應該改爲「2,33」 - 但是數字應該是「2,04」,在「4」之前應該有「0」 「 – Mike

回答

0

可能是一個更簡單的方法,但這似乎工作。 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; 
}); 
+0

sames不能工作 - 輸入不接受鍵盤輸入 – Mike

+0

似乎只能在Chrome上工作。人力資源管理。 – PherricOxide

+0

已更新爲適用於Chrome和Firefox的版本。 – PherricOxide