0

I need to have a form field accept only numbers, while allowing the user to paste into the same field. I found this js script that only allows numbers, but you can't paste numbers:

function isNumber(event) {
  if (event) {
    var charCode = (event.which) ? event.which : event.keyCode;
    if (charCode != 190 && charCode > 31 && 
       (charCode < 48 || charCode > 57) && 
       (charCode < 96 || charCode > 105) && 
       (charCode < 37 || charCode > 40) && 
        charCode != 110 && charCode != 8 && charCode != 46 )
       return false;
  }
  return true;
}

I've looked for angularjs solutions, but they suffer from the same "no pasting" issue. One would think angularjs has a built-in filter for this, but alas, no joy. SO can someone point me to some code or give me pointers to writing a filter that does this? Thanks

Ravg
  • 219
  • 4
  • 18
Lazloman
  • 1,289
  • 5
  • 25
  • 50

1 Answers1

1

Can you use HTML 5 <input type="number" />

If you need to perhaps include Modernizr.

http://modernizr.com/docs/#features-html5

BenCr
  • 5,991
  • 5
  • 44
  • 68
  • I did try type=number, but the field then includes the "rocker", which I don't want. – Lazloman Apr 02 '14 at 00:15
  • http://stackoverflow.com/questions/3975769/disable-webkits-spin-buttons-on-input-type-number – BenCr Apr 02 '14 at 08:24
  • Also http://css-tricks.com/snippets/css/turn-off-number-input-spinners/. The Input type=number also has the benefit of displaying the numeric keyboard on (some) mobile devices. – BenCr Apr 02 '14 at 08:29