如果textarea值是数字,请使用Javascript检查

时间:2012-08-15 16:28:14

标签: javascript html forms textarea

我在我的网页上有一个名为'contact_form'的表单,我在其中有一个textarea,我想在其中只允许键入数字。如何使用Javascript在提交中进行检查?

提前致谢。

1 个答案:

答案 0 :(得分: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