We can use jQuery to get the length of text in a paragraph using the JavaScript String length property. To do this we will get the text from a paragraph in the form of a string using the jQuery val() method. We will then use the length property to get the text length.
var text = $(".p1").val();
var textLength = text.length;
Let’s see a quick example of this below:
Let’s say we have the following HTML:
<div id="div1">
<p>This is a paragraph with some text.</p>
</div>
If we wanted to get the text length of the paragraph in div, #div1, then we would use the following jQuery code:
var text = $("#div1 p").val();
var textLength = text.length;
In the example above, the length of the text would be 35.
If you are using WordPress, don’t forget to change the $ to jQuery as below:
var text = jQuery("#div1 p").val();
var textLength = text.length;
Let’s do an interactive example on jQuery text length below.
Using jQuery to Get Text Length of User Input
Below we will have a simple textarea input. We will let the user enter in or write any amount of text that they want.
Here is our simple HTML:
<div id="div1">
<p>Type or paste any text you want below:</p>
<textarea type="text" id="userText"></textarea>
<div id="click-me">Get Text Length</div>
<div id="results"></div>
</div>
Once the user has entered in or written their text, we will simply use the jQuery val() method to get the user input.
Once we have the user text, we can use the length property to get the length of the user text.
Finally, we will use the jQuery text() method to update the text of our #results div.
Here is the JavaScript and jQuery code:
$("#click-me").click(function(){
var userText = $("#userText").val();
var textLength = userText.length;
$('#results').text(textLength);
});
The final code and output for this example of using jQuery to get text length is below:
Code Output:
Type or paste any text you want below:
Full Code:
<div id="div1">
<p>Type or paste any text you want below:</p>
<textarea type="text" id="userText"></textarea>
<div id="click-me">Get Text Length</div>
<div id="results"></div>
</div>
<script>
$("#click-me").click(function(){
var userText = $("#userText").val();
var textLength = userText.length;
$('#results').text(textLength);
});
</script>
Hopefully this article has been useful to help you understand how to use jQuery to get text length.
Leave a Reply