【发布时间】:2012-04-10 17:45:04
【问题描述】:
我想知道是否有可能使用 jQuery 执行以下任务:防止用户输入大于 10 或小于 0 的数字。
例如,9.10 这样的数字是可以的,但 81、10.01、11 或负数是错误的值。
为了更好地了解情况,验证是为了在测试后输入成绩。
谢谢。
【问题讨论】:
-
当然可以。你试过什么?您希望何时进行检查?模糊?提交时?
我想知道是否有可能使用 jQuery 执行以下任务:防止用户输入大于 10 或小于 0 的数字。
例如,9.10 这样的数字是可以的,但 81、10.01、11 或负数是错误的值。
为了更好地了解情况,验证是为了在测试后输入成绩。
谢谢。
【问题讨论】:
此代码仅允许您在框中输入数字,不会接受任何会使数字小于 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;
}
});
【讨论】:
如果您想在他们退出输入字段时显示某些内容,您可以使用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('');
}
});
或者,如果您想在每次击键后显示一些内容,您可以使用keyup 事件。
【讨论】:
我建议这个库: jquery-numeric
插件的主页在这里: http://code.webmonkey.uk.com/plugins/
有demo和使用可以查看源码看看使用:
http://code.webmonkey.uk.com/plugins/jquery.numeric/test.html
【讨论】: