I have a div
with contenteditable
attribute to make the div
behaves like textarea.
<div class="caption" contenteditable>
</div>
<p id="characters-count">0 characters</p>
Now, I want to check how many characters in the div using JQuery .length
property
$('.caption').keyup(function(){
var char_count = $(this).text().length;
$('#characters-count').html(char_count + " characters");
});
When I type one character, it returned '11', but when there's no character, it returned '10' in Firefox. In Chrome, it is the same, but it finally correct after I press the keyboard for the second time.
Take a look at this jsFiddle
Update: I'm using Firefox 29 and Chrome 34
just as with textareas, your div needs have no new line or spaces between the beginning and end tags.
this:
<div class="caption" contenteditable>
</div>
needs to be this:
<div class="caption" contenteditable></div>
fixed fiddle: http://jsfiddle.net/k5B32/9/
Use $.trim()
var char_count = $.trim($(this).text()).length;
Demo --->
http://jsfiddle.net/k5B32/8/
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