2011-10-29 25 views
1

我想在用戶輸入4位數字後輸入4位數字後,以表格(XXXX)驗證一年,一旦用戶輸入了4位數字我想擁有該值,以便我可以將它傳遞給阿賈克斯呼籲。旅途中的輸入驗證

<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); 
}); 

回答

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); 
      } 
     } 
    }); 

}); 
+0

可怕的,除非你希望人們進入年2千年以前,或者7的未來。 –

+0

@Kolink是的,我的不好,我在你評論的同時加入了這一點。 – attack

+0

那個看起來不錯,對我來說...... – killkrazy

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...'); 
    } 
}); 

和..