Use JQUERY to limit characters allowed in an input textbox control

As mentioned in a prior post JQUERY enhances the front end by improving the user experiences by allowing a page to be more responsive to user actions. For example, take the ability to limit the characters typed into a text box control on a web page. It is possible to use JQUERY to display for the user the numbers of additional characters allowed so they do not exceed the maximum characters. In a recent application I tested out a JQUERY function to do just that. In this test application, you enter a word and it scrambles the words into numerous permutations. The idea was to create an anagram solver, however it turns out it is a great word scrambler application.

Code to display the number of remaining characters

It displays an alert in case the user attempts to add more characters than we permit which in this case is 20 characters. The id of the input control is “input” so the JQUERY selector references #input.


  var the_input_len;
  var the_input;

if (the_input_len>=0) {
 $('#charcounter').html(the_input_len + ' characters remaining');  //code
  alert('Sorry, the text is too long. The maximum character length is 20.');
   $('#input').val($('#input').val().slice(0, 20));

View the demo project here.

About the demo project: It allows input of up to 20 characters and using the same approach as the above JQUERY it dispalys a message if the user tries to type in more characters than allowed. The application is using PHP and JQUERY to generate an output of scrambled text.