我希望在用户输入4位数后,在表格(XXXX)中验证一年,一旦用户输入了4位数字,我想拥有该值,这样我就可以将其传递给ajax调用。
<h6>What year was the car manufactured</h6>
<input name="car_year" type="text">
<div class="car_make_error car_year_error">Car Year Error</div>
jquery的:
$("input[name='car_year']").change(function() {
validate to make sure 4 digits are in the proper range and get the value of the
4 digits
}
我知道我可以使用密钥,但我不确定如何获得任何帮助。
修改
我用过这段代码:
$(car_year).keyup(function() {
var year = $(this).attr('value');
$('.car_year').html(year);
});
答案 0 :(得分:2)
看起来你已经走在正确的轨道上了。这是你需要的吗?
$(function() {
var LOWER_RANGE = 2000;
var UPPER_RANGE = 2020;
var $carYearInput = $('#car_year');
$carYearInput.keyup(function() {
var value = $carYearInput.val();
// Check that we were given 4 numbers
if(value.match(/^[0-9]{4}$/))
{
// Convert the value to an int
var year = parseInt(value, 10);
// Check that the year is in range
if(year > LOWER_RANGE && year < UPPER_RANGE)
{
alert(year);
}
}
});
});
答案 1 :(得分:1)
这样的事情:
$('#car_year').keyup(function() {
var year = parseInt($(this).attr('value')); // parseInt forces the value to int
var min = 1965;
var max = 2011;
if (year <= max && year >= min) {
// Will only go in here if it is an four digit integer between min and max
$('#result').html('Yeah, looks ok!');
} else {
$('#result').html('Not a proper year...');
}
});
和..