2012-04-10 66 views
0

我想知道是否有可能与jQuery执行以下任务:防止用户输入一个大于10或小于0jQuery脚本来验证号在进入

例如,数像9.10是好的,但81,101,11或负数是错误的值。

为了更好地了解情况,验证是在测试后输入成绩。

谢谢。

+3

当然这是可能的。你有什么尝试?你什么时候想要检查发生?模糊?提交? – 2012-04-10 17:55:42

回答

2

此代码将只允许您在框中输入数字,也不会接受任何输入,将使小于0的数量和大于10

var $grade = $('#grade'); 

$grade.keydown(function (e) { 
    var code = e.which, 
     chr = String.fromCharCode(code), // key pressed converted to s string 
     cur = $grade.val(), 
     newVal = parseFloat(cur + chr); // what the input box will contain after this key press 

    // Only allow numbers, periods, backspace, tabs and the enter key 
    if (code !== 190 && code !== 8 && code !== 9 && code !== 13 && !/[0-9]/.test(chr)) { 
     return false; 
    } 

    // If this keypress would make the number 
    // out of bounds, ignore it 
    if (newVal < 0 || newVal > 10) { 
     return false; 
    } 

}); 

http://jsfiddle.net/WPdVq/

1

如果你想为他们退出输入字段中显示的东西,你可以使用change event

$('.target').change(function() { 
    if($(this).val() > 10) { 
     // Do something, like warn them and/or reset to empty text. 
     alert('Greater than 10.'); 
     $(this).val(''); 
    }  
});   

jsfiddle working example

另外,如果你想显示每个按键后的东西,你可以使用keyup事件。

+0

看起来不错,谢谢。它可以更新,所以它只会接受数值和点? – Psyche 2012-04-10 20:27:14

+0

查看[无效代码]的[答案](http://stackoverflow.com/a/10096685/448876)。他有更完整的答案,包括你的要求。 – absynce 2012-04-11 19:08:29