How can I count the number of characters in a textbox using jQuery?
$("#id").val().length < 3  just counts upto 3 character spaces but not the number of characters.
value. length; document. getElementById(displayto). innerHTML = len; } </script> <textarea id="data" cols="40" rows="5" onkeyup="countChars('data','charcount');" onkeydown="countChars('data','charcount');" onmouseout="countChars('data','charcount');"></textarea><br> <span id="charcount">0</span> characters entered.
For length including white-space:
$("#id").val().length  
For length without white-space:
$("#id").val().replace(/ /g,'').length   For removing only beginning and trailing white-space:
$.trim($("#test").val()).length   For example, the string " t e s t " would evaluate as:
//" t e s t " $("#id").val();   //Example 1 $("#id").val().length; //Returns 9 //Example 2 $("#id").val().replace(/ /g,'').length; //Returns 4 //Example 3 $.trim($("#test").val()).length; //Returns 7   Here is a demo using all of them.
Use .length to count number of characters, and $.trim() function to remove spaces, and replace(/ /g,'') to replace multiple spaces with just one. Here is an example:
   var str = "      Hel  lo       ";    console.log(str.length);     console.log($.trim(str).length);     console.log(str.replace(/ /g,'').length);   Output:
20 7 5  Source: How to count number of characters in a string with JQuery
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With