2017-05-05 108 views
0

我的onChange函數有問題。我想要做的是,當用戶進入輸入並且不用添加任何值而輸出時,它應該指示輸入是空的。對於文本框它不起作用。和輸入年份一樣,應該有4個數字,但是當輸入4個數字時,它會給出一個錯誤信息,我可以告訴它在輸入最後一個數字之前得到的值。我怎麼能解決這個問題?謝謝!Jquery:OnChange函數的延遲

<script> 

      //Here is the number validation function 
      $(document).ready(function(){ 
       $("input").keydown(function(a){ 
        var howMany = 0; 
        //Here I am getting the key code and making it into a string 
        a = String.fromCharCode(a.keyCode); 
        //Here I make the other keys I want to use and 
        //Storing them into variables 
        var backspaceKey = String.fromCharCode(8); 
        var tabKey = String.fromCharCode(9); 
        var enterKey = String.fromCharCode(13); 
        howMany = $("#year").val(); 
        //Validating the input here, no more than 4 numbers and 
        //backspace and other functional keys are included 
        if(howMany.length > 3){ 
         if(a == backspaceKey || 
          a == tabKey || 
          a == enterKey){ 
          return true; 
         }else{ 
          return false; 
         } 
        } 
       }); 

       $("#year").on('change',function(){ 
        if(!$("#year").val()){ 
         alert("empty"); 
         emptyBox("#year"); 
         errorBox("#year"); 
         return false; 
        }else if($("#year").val() != 4){ 
         errorBox("#year"); 
         alert("short num"); 
        } 
       }); 

       $("#submit").click(function(){      
        var year = $("#year").val(); 
        var description = $("#description").val(); 

        if(!$.trim($("#year").val())){ 
         alert("True year"); 
         emptyBox("#year"); 
         errorBox("#year"); 
         return false; 
        } 

        if(!$.trim($("#description").val())){ 
         alert("true" + description); 
         emptyBox("#description"); 
         errorBox("#description"); 
         return false; 
        } 
       }); 
      }); 


      //Takes away the error 
      function validated(name){ 
       //$(name).after 
      } 


      //checks if its empty 
      function emptyBox(name){ 
       $(name).after("<p class='text-center'>Error, Cannot be empty</p>"); 
      } 

      //Function that changes the color of the input box if error 
      function errorBox(name){ 
       $(name).css({ 
        border: "2px solid red" 
       }) 
      } 
     </script> 





<label for="year">Year</label> 
        <input type="number" class="form-control year" id="year" placeholder="Enter the Year of Event" onchange="year()"> 
        <br> 
        <lable for="description">Description</lable> 
        <textarea id="description" class="form-control" placeholder="Describe the Event"></textarea> 

DEMO:https://jsfiddle.net/efoc/tx51jj2v/

+0

小提琴鏈接是沒有幫助的。您已將所有代碼放在HTML中。請整理你的小提琴。 –

+0

我創建了一個簡單的示例,請參閱https://jsfiddle.net/oddFeb/f2e4md3u/ –

回答

0

一個建議來實現輸入與大小不超過4個字符是簡單地使用maxlength屬性。

,否則這將是更好地檢查val的長度,如果條件,如:

$("#year").val().length > 0