Reputation: 87
I need to count the characters of the content in textarea and show it at the below in a specific class.
I'm using the code below which doesn't work for me:
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$(".messageText").each(function(){
$(this).next(".messageCharacters").text($(this).val().length);
$(this).next(".messagePages").text(($(this).val().length / 70).toFixed());
});
$(".messageText").keyup(function(){
$(this).next(".messageCharacters").text($(this).val().length);
$(this).next(".messagePages").text(($(this).val().length / 70).toFixed());
});
});
</script>
<p>
<textarea name="title1" class="messageText">phrase1</textarea>
<br /><span class="messageCharacters">0</span> characters - <span class="messagePages">0</span> pages
</p>
<p>
<textarea name="title2" class="messageText">phrase2</textarea>
<br /><span class="messageCharacters">0</span> characters - <span class="messagePages">0</span> pages
</p>
How should I fix it?
Upvotes: 1
Views: 67
Reputation: 206028
First of all your $(".messageText").keyup(function(){
is outside the document.ready
function, therefore your .messageText
element are not collected by the DOM parser.
Also .next()
element is <br>
so either you need to target a parent container or do a .nextAll()
like:
$(function(){ // DOM ready shorthand
function count() {
$(this).nextAll(".messageCharacters").text(this.value.length);
$(this).nextAll(".messagePages").text((this.value.length/70).toFixed());
}
$(".messageText").each(count).on("input", count);
});
to prevent one copy-pasteing text inside your textarea (using mouse right click - paste) and your script doing nothing use .on("input")
to register any change inside the textarea value listener.
Also think about ($(this).val().length/70).toFixed()
if initially 34 characters makes it pages=2
only at 105 you'll get pages=3
. So review that math again.
Upvotes: 2
Reputation: 33870
The element next to your .messageText
is the br
, so $(this).next(".messageCharacters")
will never return your element.
Use .nextAll()
instead :
$(this).nextAll(".messageCharacters")
Upvotes: 2