title: How can I restrict number of character input in a field with javascript or jquery?
body: <p>I wrote a validation code for an input text field, which will take only numbers and some control keys. I took the help from stackoverclow :), So I am here again to take the help. My validation code is   </p>
  
  <pre><code> $("#txtLevel1Year").keydown(function(event)
              {
                  // Allow only backspace,delete,left arrow,right arraow and Tab
                  if ( event.keyCode == 46 
                      || event.keyCode == 8 
                      || event.keyCode == 37 
                      || event.keyCode == 39 
                      || event.keyCode == 9)
                      {
                      // let it happen, don't do anything
                      }
                      else {
                          // Ensure that it is a number and stop the keypress
                          if ((event.keyCode &lt; 48 || event.keyCode &gt; 57) &amp;&amp; (event.keyCode &lt;96 ||event.keyCode &gt; 105) ) {
                              event.preventDefault(); 
                          }   
                      }
              });
  </code></pre>
  
  <p>Now let me tell you what I am looking for, first, I want to restrict this field to take exactly 4 digits.not less not more, the second one is about optimization.
  The text field(s) where I want this validation to work is(are)</p>
  
  <pre><code>&lt;asp:TextBox runat="server" ID="txtLevel1Year" Width="50px" TabIndex="13"&gt;&lt;/asp:TextBox&gt;  
                          &lt;asp:TextBox runat="server" ID="txtLevel2Year" Width="50px" TabIndex="17"&gt;&lt;/asp:TextBox&gt;  
                          &lt;asp:TextBox runat="server" ID="txtLevel3Year" Width="50px" TabIndex="21"&gt;&lt;/asp:TextBox&gt;  
                          &lt;asp:TextBox runat="server" ID="txtLevel4Year" Width="50px" TabIndex="25"&gt;&lt;/asp:TextBox&gt;  
  </code></pre>
  
  <p>Here I can repeat the the validation code 4 times to make this work by grabing four different ids though the validation is exactly same. Can I do anything which can remove this repeatation? If My problem isw not clear to you, please let me know.
  thanx all of you in advance. 
  This is the edited part of this question I have achieved the goal of optimazation by creatinf a CSS class and call it in the div where I place all the year text boxes. But My limit to make it exactly 4 digits yet to be solved. please help me. </p>