2017-05-05 63 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