-5

I have in my webpage a form called 'contact_form' and I have in it a textarea where I want to allow to type only numbers inside. How do I check it in submission with Javascript?

Thanks in advance.

dda
  • 6,030
  • 2
  • 25
  • 34
MichBoy
  • 299
  • 1
  • 4
  • 13
  • 2
    What have your tried so far? Could you post your code. – devang Aug 15 '12 at 16:30
  • possible duplicate of [Restricting input to textbox: allowing only numbers and decimal point](http://stackoverflow.com/questions/2808184/restricting-input-to-textbox-allowing-only-numbers-and-decimal-point) – Fluffeh Aug 16 '12 at 11:33

1 Answers1

1

HTML:

<textarea id="text"></textarea>​

JavaScript:

var re=/\d/,
    allowedCodes = [37, 39, 8, 9], // left and right arrows, backspace and tab
    text = document.getElementById('text');

text.onkeydown = function(e) {
    var code;
    if(window.event) { // IE8 and earlier
        code = e.keyCode;
    } else if(e.which) { // IE9/Firefox/Chrome/Opera/Safari
        code = e.which;
    }
    if(allowedCodes.indexOf(code) > -1) {
        return true;
    }
    return !e.shiftKey && re.test(String.fromCharCode(code));
};​

Demo

Eugene Naydenov
  • 7,165
  • 2
  • 25
  • 43