2013-03-29 28 views
2

我有一個任務來限制文本框從字母值。只有浮點值是可能的。小數點後面我們必須寫出兩位數字。我這樣做了,但它不適用於Mozilla Firefox。我怎麼解決這個問題?按鍵不工作在Mozila Firefox

我的劇本是

$(function() { 
    $('#name').bind('paste', function() { 
     var self = this; 
     setTimeout(function() { 
      if (!/^[a-zA-Z]+$/.test($(self).val())) $(self).val(''); 
     }, 0); 
    }); 

    $('#salary').bind('paste', function() { 
     var self = this; 
     setTimeout(function() { 
      if (!/^\d*(\.\d{1,2})+$/.test($(self).val())) $(self).val(''); 
     }, 0); 
    }); 

    $('.decimal').keypress(function (e) { 
     var character = String.fromCharCode(e.keyCode) 
     var newValue = this.value + character; 
     if (isNaN(newValue) || hasDecimalPlace(newValue, 3)) { 
      e.preventDefault(); 
      return false; 
     } 
    }); 

    function hasDecimalPlace(value, x) { 
     var pointIndex = value.indexOf('.'); 
     return pointIndex >= 0 && pointIndex < value.length - x; 
    } 
    function isNumberKey(evt) { 
     var charCode = (evt.which) ? evt.which : event.keyCode 

     if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46) 
      return false; 
     else { 
      var len = document.getElementById("txtChar").value.length; 
      var index = document.getElementById("txtChar").value.indexOf('.'); 

      if (index > 0 && charCode == 46) { 
       return false; 
      } 
      if (index >0 || index==0) { 
       var CharAfterdot = (len + 1) - index; 
       if (CharAfterdot > 3) { 
        return false; 
       } 

} 

     } 
     return true; 
     } 
}); 

HTML是

<b>Name</b> 
<input type="text" id="name" /><br/> 
<b>Salary</b> 
<input type="text" id="txtChar" onkeypress="return isNumberKey(event)" name="txtChar" class="CsstxtChar" /> 
+3

我相信這是第四次我看到相同的代碼在2天內..實際上,你可以計算出任何自己? – Rob

+0

如果您在輸入上使用數字類型,您已經解決了所有問題! – adeneo

+0

檢查的螢火控制檯 –

回答

4
function isNumberKey(evt) { 
    var charCode = (evt.charCode) ? evt.which : event.keyCode 

    if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46) 
     return false; 
    else { 
     var len = document.getElementById("txtChar").value.length; 
     var index = document.getElementById("txtChar").value.indexOf('.'); 

     if (index > 0 && charCode == 46) { 
      return false; 
     } 
      if (index >0 || index==0) { 
       var CharAfterdot = (len + 1) - index; 
       if (CharAfterdot > 3) { 

        return false; 
       } 

} 

     } 
     return true; 
     } 





<input type="text" id="txtChar" onkeypress="return isNumberKey(event)" name="txtChar" class="CsstxtChar" /> 
+0

感謝莫妮卡,它是一個魅力工作.. :) – BNN

+0

應該有一個;在「var charCode =(evt.charCode)?evt.which:event.keyCode」..結束時......只是一個建議......無論如何都是推薦:) –

5

你應該改變e.keyCode到e.charCode。

String.fromCharCode(e.charCode)