2017-12-27 915 views
0

我想在輸入時檢查輸入值,但我的代碼似乎不工作(工作片段,但MVC VS 2013)
我的代碼有問題嗎?在輸入時檢查輸入(僅限數字)

$(document).ready(function(){ 
 

 
     $('#txtAge').keyup(function(){ 
 
      var pattern = /^\d+$/; 
 
      if(pattern.test($(this).val()) && $(this).val()!=''){ 
 

 
       $("#age_error_message").hide(); 
 
       $("#txtAge").css('border-bottom', '2px solid #34F458'); 
 
      } 
 
      else if ($(this).val() =='') { 
 
       $("#age_error_message").html("Please enter your age"); 
 
       $("#age_error_message").show(); 
 
       $("#txtAge").css('border-bottom', '2px solid #F90A0A'); 
 
       
 
      } 
 
      else { 
 
       $("#age_error_message").html("Should contain number only"); 
 
       $("#age_error_message").show(); 
 
       $("#txtAge").css('border-bottom', '2px solid #F90A0A'); 
 
       
 
      } 
 

 
     }); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"> 
 
</script> 
 
Age: <input name="age" id="txtAge" type="text" class="btn-sm form-control " placeholder="Your age" /> 
 
<span class="error-form btn-sm text-danger" id="age_error_message"></span>

+1

你的代碼在這裏工作得很好,問題是什麼? –

+0

控制檯中是否有錯誤? –

回答

2

改變這樣的。你的代碼工作正常

$('#txtAge').keyup(function(){ 
     var pattern = /^\d+$/; 
     if(pattern.test($(this).val()) && $(this).val()!=''){ 

      $("#age_error_message").hide(); 
      $("#txtAge").css('border-bottom', '2px solid #34F458'); 
     } 
     else if ($(this).val() =='') { 
      $("#age_error_message").html("Please enter your age"); 
      $("#age_error_message").show(); 
      $("#txtAge").css('border-bottom', '2px solid #F90A0A'); 

     } 
     else { 
      $("#age_error_message").html("Should contain number only"); 
      $("#age_error_message").show(); 
      $("#txtAge").css('border-bottom', '2px solid #F90A0A'); 

     } 

    }); 

驗證.. https://jsfiddle.net/knv8grt6/

+0

我沒有看到任何代碼的變化。你有OP的代碼的確切副本。 –

0

這似乎我的代碼does not工作BCZ我把多函數「腳本「標籤。當我創建新的'腳本'標籤,然後把我的代碼,它工作正常。有人可以解釋嗎?