1. 程式人生 > >input標籤只能輸入數字小數點 且小數點後只有兩位 ,不允許存在兩個小數點!!

input標籤只能輸入數字小數點 且小數點後只有兩位 ,不允許存在兩個小數點!!

$("#open").on('keyup', function (event) {

   var $amountInput = $(this);
   var tmptxt=$(this).val();
   //$(this).val(tmptxt.subString(0,1) + '.' + tmptxt.subString(2));

    var FirstChar=tmptxt.substr(0,1);

//使用字元分離獲取輸入的第一位

    var SecondChar=tmptxt.substr(1,2);
   // 使用字元分離獲取輸入的第二位
     if(FirstChar=="0"){
   SecondChar.replace(/[0,1,2,3,45,6,7,8,9]/,"0.");

    }

//如果第一位是0,將第一位替換成0.

  // $(this).val(tmptxt.replace(/\D|^0/g,''));
   event = window.event || event;
   if (event.keyCode == 37 | event.keyCode == 39) {
       return;
   }
   //先把非數字的都替換掉,除了數字和. 
   $amountInput.val($amountInput.val().replace(/[^\d.]/g, "").
       //只允許一個小數點              
       replace(/^\./g, "").replace(/\.{2,}/g, ".").
       //只能輸入小數點後兩位
       replace(".", "$#$").replace(/\./g, "").replace("$#$", ".").replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'));
           });
$("#open").on('blur', function () {
   var $amountInput = $(this);
   //最後一位是小數點的話,移除
   $amountInput.val(($amountInput.val().replace(/\.$/g, "")));
});