2016-10-26 45 views
0

我必須定義僅接受整數的輸入文本。將輸入字段設置爲僅接受帶有jQuery的數字

我試着用正則表達式,但值的小數部分仍然可見。

我用這個功能:

$(document).on("input","input", function(e) { 
    this.value = this.value.replace(/[^\d\\-]/g,''); 
}) 
+0

爲什麼不使用型號? – guradio

+0

但它也接受輸入中的小數點(。),我沒有在輸入中需要(。)。 – durga

回答

0
Finally I solved the above issue with my requirement to type only number is 

$(document).on("input", ".skilltxt", function(e) { 
       this.value = this.value.replace(/[^\d]/g,''); 
      }); 
      $(".skilltxt").on('paste',function(e) { 

        if(gBrowser=='IE') { 
         var clipboardData, pastedData; 
         clipboardData = e.clipboardData || window.clipboardData; 
          pastedData = clipboardData.getData('Text'); 

        } 
        else if((gBrowser=='Firefox')|| (gBrowser=='Chrome')){ 
          var pastedData = (e.originalEvent || e).clipboardData.getData('text/plain'); 
          window.document.execCommand('insertText', false, pastedData) 
        } 
       if(Math.floor(pastedData) == pastedData && $.isNumeric(pastedData)){ 
        $(this).val($(this).val().replace(/[^\d]/g,'')); 
        } 
        else{ 
        return false; 
        } 
      }); 
0

簡單,使用方便。試試看: 已修改:也請撥打onblur事件以防粘貼。

function numOnly(selector){ 
 
    selector.value = selector.value.replace(/[^0-9]/g,''); 
 
}
<input type="text" onkeyup="numOnly(this)" onblur="numOnly(this)">

+0

右鍵單擊並粘貼不會觸發鍵控。 – Archer

+0

謝謝@阿徹,以前我沒有想過。現在它是固定的。現在檢查。 – AHJeebon

0

您可以在​​檢測是否爲數字,你可以粘貼事件是否是數字,並刪除所有非數字。這也刪除點。

原始來源:keydown detectPaste remove

此代碼下面已經從初始源進行修改。

請嘗試:

$("#input").on("paste", function() { 
 
    setTimeout(function(){ 
 
    if ($('#input').val() != $('#input').val().replace(/\D/g,"")) 
 
    { 
 
     $('#input').val($('#input').val().replace(/\D/g,"")); 
 
    } 
 
    },10) 
 
}); 
 

 
$('#firstrow').on('keydown', '#input', function(e){-1!==$.inArray(e.keyCode,[46,8,9,27,13])||/65|67|86|88/.test(e.keyCode)&&(!0===e.ctrlKey||!0===e.metaKey)||35<=e.keyCode&&40>=e.keyCode||(e.shiftKey||48>e.keyCode||57<e.keyCode)&&(96>e.keyCode||105<e.keyCode)&&e.preventDefault()});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="firstrow"> 
 
    <input id="input" type="text"> 
 
</div>

0

這件怎麼樣?

$('input').on('input blur paste', function(){ 
 
$(this).val($(this).val().replace(/\D/g, '')) 
 
})
<input> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

相關問題