Hello friends, In this tutorial you are going to see how to write a jQuery script which should display the no. of characters entered in a textbox realtime.
This script could be very much useful if you want show the user how many characters the user has entered into a text box or textarea. Especially works with form validations with character limit etc.,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<!DOCTYPE html> <html> <head> <title>jQuery script to count the no. of characters in a textbox</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script> $(function () { //lets use the jQuery Keyboard Event to catch the text typed in the textbox $('#txtbox').keyup(function () { //.val() will give the text from the textbox and .length will give the number of characters var txtlen = $(this).val().length; //.replace used here to replace the space in the string and .length is to count the characters var txtlennospace = $(this).val().replace(/\s+/g, '').length; //the below lines will display the results $('#txtbox_count').text(txtlen); $('#txtbox_count_no_space').text(txtlennospace); }); }); </script> </head> <body> <div style="padding-bottom: 10px;">jQuery - Realtime character counter</div> <div> Enter your text: <input style="padding: 7px;" maxlength="60" size="50" type="text" id="txtbox" /> <p>No. of characters with space : <span id="txtbox_count"></span></p> <p>No. of characters without space : <span id="txtbox_count_no_space"></span></p> </div> </body> </html> |
The above script is much simpler than you think. Just read the comments to understand what each lines are doing in the above script.
You can see the demo here: