Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery '.length' property returns incorrect value when checking characters length in a div

Tags:

jquery

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

like image 321
Abednego Avatar asked Sep 30 '22 21:09

Abednego


2 Answers

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/

like image 142
kennypu Avatar answered Oct 03 '22 11:10

kennypu


Use $.trim()

var char_count = $.trim($(this).text()).length;

Demo ---> http://jsfiddle.net/k5B32/8/

like image 42
Mohammad Adil Avatar answered Oct 03 '22 10:10

Mohammad Adil