Home Ask Login Register

Developers Planet

Your answer is one click away!

Ben February 2016

Why jQuery .length isn't updated?

I'm trying to make a character counter with a "success" message.

My problem is that after the user has reached the desired number of characters and the "success" message is displayed, if he erases characters the "success" message stays.

I would think it would calculate every "keyup" but I guess I'm missing something. Would appreciate any ideas.

Here is the code:

$('textarea').on('keyup', function() {
    if ($(this).val().length < 10) {
        $('#count').text(10 - $(this).val().length);
    } else {
      $('.enoughText').text('ok now.');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p class="enoughText">you have more <span id="count"></span> to go.</p>


Henk-Jan Leusink February 2016

The problem is that you update the whole paragraph with the class .enoughText. If 10 is reached the span with the ID count will be removed.

My suggestion:

if ($(this).val().length < 10) {
  $('.enoughText').text('you have more ' + (10 - $(this).val().length) + ' to go.');
} else {
  $('.enoughText').text('ok now.');

Nick Zuber February 2016

Working Fiddle

The issue was when you were writing the success text, you were overwriting the area of the code that you stored your counter.

To resolve this, you can just work with everything in the same container:


<p class="response">you have more 10 to go.</p>


if($(this).val().length < 10) {
    $('.response').text("you have more " + parseInt(10 - $(this).val().length, 10) + " to go.");
    $('.response').text('ok now.');

Post Status

Asked in February 2016
Viewed 2,068 times
Voted 7
Answered 2 times


Leave an answer

Quote of the day: live life