Javascript / Jquery:使用数字范围验证输入 [英] Javascript/Jquery: validate input with a number range
本文介绍了Javascript / Jquery:使用数字范围验证输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在预先配置的数字范围内验证输入字段。
只允许1到24之间的数字。
I'd like to validate an input field within a preconfigured range of numbers. Only numbers from 1 up to 24 are allowed.
我该怎么办?
使用这样的自定义解决方案:
With a custom solution like this:
$('.field').keypress(function(event) {
var val = parseInt($(this).val()) + HERE_I_SHOULD_SUM_THE_NEWLY_ADDED_DIGIT;
if(val < 1 || val > 24) event.preventDefault();
});
我能够检索当前的输入值。
如何添加新添加的数字?
I'm able to retrieve the current input value. How can I add the newly added digit?
推荐答案
这样的事情怎么样?
$("input").on("change", function() {
var val = Math.abs(parseInt(this.value, 10) || 1);
this.value = val > 25 ? 24 : val;
});
DEMO: http://jsfiddle.net/3jw4S/
这篇关于Javascript / Jquery:使用数字范围验证输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文