最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Delete all non-numerical characters in input field on paste event Javascript - Stack Overflow

programmeradmin1浏览0评论

I have a html with several fields. One of the field allows only numerical input. But now I want that when user performes paste into that field all characters, except numbers where stripped or deleted.

For example user paste:

$1 234 567 -> 1234567 in input field

1.234.567 -> 1234567

1,234,567 -> 1234567

and so on

I have a html with several fields. One of the field allows only numerical input. But now I want that when user performes paste into that field all characters, except numbers where stripped or deleted.

For example user paste:

$1 234 567 -> 1234567 in input field

1.234.567 -> 1234567

1,234,567 -> 1234567

and so on

Share Improve this question asked Aug 21, 2012 at 7:49 halofourteenhalofourteen 1,0002 gold badges10 silver badges18 bronze badges 2
  • Is “-” (used as minus sign) numeric? In general, it’s not a good idea to silently delete characters from user input. If I meant to order 100 items but somehow managed to type 1oo instead, I’d like to be warned and prompted for a correction, rather than having my order silently changed to 1 item. – Jukka K. Korpela Commented Aug 21, 2012 at 8:14
  • Thanks for comment, i'll keep it in mind for future. At this time i have to solve only this pattern. – halofourteen Commented Aug 21, 2012 at 8:38
Add a comment  | 

3 Answers 3

Reset to default 13

use regex.

<input id="inputBox" name="inputBox" />
<script type="text/javascript">
var inputBox = document.getElementById('inputBox');
inputBox.onchange = function(){
    inputBox.value = inputBox.value.replace(/[^0-9]/g, '');
}
</script>​

or you could use a timer to constantly check that field.

<input id="inputBox" name="inputBox" />
<input id="inputBox2" name="inputBox2" />
<script type="text/javascript">
var timer = new Array();
function checkFields(el){
    var inputBox = document.getElementById(el);
    inputBox.value = inputBox.value.replace(/[^0-9]/g, '');
    clearTimeout(timer[el]);
    timer[el] = setTimeout((function(){ checkFields(el); }), 50);
};
function timerFields(el){
    timer[el] = setTimeout((function(){ checkFields(el); }), 50);
};
timerFields('inputBox');
timerFields('inputBox2');
</script>​

try this

var regexp=/\D/g;
alert(("$1 234 567").replace(regexp,""));
var f = function (s) { 
  var r = ''; 

  for (var i in s) {
    if ('0' <= s[i] && s[i] <= '9') {
      r += s[i]; 
    }
  }

  return r;
}

alert(f('123.234-234?345')); // 23234234345

But use regexp from another answer :)

发布评论

评论列表(0)

  1. 暂无评论