如何修复js中的剩余字符计数器

问题描述 投票:0回答:1

我将为 HTML 文本区域创建一个 javascript 剩余字符计数器。但我的代码不起作用。我该如何解决这个问题。

$(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>

javascript html textarea charactercount
1个回答
0
投票

代码中的问题:页面加载时未初始化剩余字符数,并且计数器仅在键入后更新,即使设置了 maxlength。

我添加的内容:我在页面加载时将剩余字符数初始化为 160,并使用 .text() 在用户键入时动态更新计数,确保其准确反映剩余字符。

$(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>

© www.soinside.com 2019 - 2024. All rights reserved.