javascripthtmltextareacharactercount

How can fix the remainning characters counter in js


I will create a javascript remaining character counter for an HTML textarea. But my code is not working. How can I fix this.

$(document).ready(function(){

  var length = 0;
  var maximumCharacters = 160;

  $('#description').keyup(function(){
    length = this.value.length;

    if(length > maximumCharacters){

      return false;

    } else if (length > 0){

      $("#remaining-characters").html("Remaining characters: " + (maximumCharacters-length));

    } else {

      $("#remaining-characters").html("Remaining characters: " + maximumCharacters);

    }
  })
})
<div class="row mb-3">
        <label for="description" class="col-sm-2 col-form-label label">Description</label>
        <div class="col-sm-10">
          <textarea class="form-control form textarea" id="description" name="description" maxlength="160"></textarea><span id="remaining-characters"></span>
        </div>
      </div>


Solution

  • Issue in your code: The remaining character count wasn't initialized on page load, and the counter only updated after typing, even though maxlength was set.

    What I added: I initialized the remaining characters count to 160 on page load and used .text() to update the count dynamically as the user types, ensuring it reflects the remaining characters accurately.

    $(document).ready(function() {
        var maximumCharacters = 160;
    
        // Initialize the remaining characters when the page loads
        $("#remaining-characters").text("Remaining characters: " + maximumCharacters);
    
        $('#description').keyup(function() {
            var length = this.value.length;
    
            // Update the remaining characters
            if (length <= maximumCharacters) {
                $("#remaining-characters").text("Remaining characters: " + (maximumCharacters - length));
            }
        });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <div class="row mb-3">
        <label for="description" class="col-sm-2 col-form-label label">Description</label>
        <div class="col-sm-10">
            <textarea class="form-control form textarea" id="description" name="description" maxlength="160"></textarea>
            <span id="remaining-characters"></span>
        </div>
    </div>