2016-11-08 13 views
2

私は入力として数値を入力したいので、数字の入力を使用しているプロジェクトがありますが、これも小数点の区切り文字を使用できます。,.eの使用をどのように防止できますか?数字入力のみ

私は周りを見回し、希望の結果を得たものを見つけることができず、10進入力をブロックしなかったか、またはユーザーが引き続きフィールドに貼り付けることができるようになりました。

私は使用できるjavascriptとjqueryを持っていますが、私は外部librairyを使いたくありません。

誰かが私を助けることができるなら、それはappriciatedとなるでしょう。

function LimitKeys($id) {   
    $field = document.getElementById($id); 
    $value = $($field).val(); //if the value contains multiple e , or . the value is no longer valid and gives me blank 
    console.log($value); 
    $regex = /[^\d]/; 

    $val = $value.replace($regex, "");// cant replace in blank 
    console.log($val); 
    //$($field).val($val); 
} 

$('.number-only').keypress(function (event) { //sinds it's on keypress it won't catch the paste of data. 
    console.log(this.value); 
    var regex = new RegExp("^[0-9]+$"); 
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode); 
    if (!regex.test(key)) { 
     event.preventDefault(); 
     return false; 
    } 
}); 
+0

試してみてください:$( '。数字のみ')。入力(function(){this.value = this.value.replace(/ \ D/g、 '')} ' –

+0

@ Liam数字0-9と私はそれはそれほど珍しい質問ではないので、前に尋ねられていると仮定しますが、私は検索でそれを見つけられませんでした、または私のニーズを十分に満たしていない答えを持っています – maam27

答えて

1

エラークラスを作成することを忘れないでください、このコード

$(".number-only").on('input', function (e) { 
//if the letter is not digit then display error and don't type anything 
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) { 
    //display error message 
    $(".error").html("Only numbers allowed").show().fadeOut("slow"); 
      return false; 
} 
}); 

を試してみてください。

+0

これはkeypressであるため、貼り付けられているコンテンツをフィルタリングすることはありません。これは、私が投稿した2番目の関数で唯一の問題です。 – maam27

+0

@ maam27 onBlurをこの – abhirathore2006

+1

とともに使用して、 'on() 1つのルール内のイベントリスナー[この回答を確認](http://stackoverflow.com/questions/2534089/jquery-multiple-events-to-trigger-the-same-function#answer-2534107) –

関連する問題