最大长度不同的两个文本区域的字符数

时间:2019-10-28 16:46:00

标签: javascript jquery jquery-selectors getelementbyid getelementsbyclassname

我想获得两个具有不同最大长度的文本区域的字符数。但是,我相信我与它们的ID(用于实现其50和100的不同最大长度)存在一些冲突。

当通过修改其类和id仅用于一个文本区域时,jQuery代码可以正常工作。但是,当我使用它时,它对于两个都根本不起作用

 var myText = document.querySelectorAll('#myTextOne, #myTextTwo').maxLength;

不重复:有人在Perform character count on different textarea id中问了类似的问题。但是,他们对所有文本区域使用相同的最大长度,这不是我的情况。我正在使用textareas的ID来获取其特定字数。

function showCounter() {
  $('.counter-1, .counter-2').css({
    display: 'inline-block'
  });
}

function hideCounter() {
  $('.counter-1, .counter-2').css({
    display: 'none'
  });
}

var myText = document.querySelectorAll('#myTextOne, #myTextTwo').maxLength;

$(document).ready(function() {
  var maxLength = myText;

  $('textarea').keyup(function() {

    var getTextCount = $(this).val();
    var charCount = maxLength - getTextCount.length;
    var safePercent = (maxLength * 80) / 100;

    if (getTextCount.length <= safePercent) {
      $('.counter-1, .counter-2').html(charCount);
      $('.counter-1, .counter-2').css({
        'color': 'blue'
      });
    } else {
      $('.counter-1, .counter-2').html(maxLength - getTextCount.length);
      $('.counter-1, .counter-2').css({
        'color': 'red'
      });
    }
  });
});
.wrapper {
  display: inline-block;
}

.textbox>textarea {
  width: 200px;
  height: 50px;
  padding: 10px;
}

.counter-1,
.counter-2 {
  display: noane;
  font-size: 10px;
  color: blue;
  float: right;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="wrapper">

    <!-- First textarea -->
    <div class="textbox">
      <textarea id="myTextOne" maxlength="50" onclick="showCounter()" onfocusout="hideCounter()" placeholder="Write something..."></textarea>
    </div>
    <div class="counter-1"></div>

    <!-- Second textarea -->
    <div class="textbox">
      <textarea id="myTextTwo" maxlength="100" onclick="showCounter()" onfocusout="hideCounter()" placeholder="Write something..."></textarea>
    </div>
    <div class="counter-2"></div>
  </div>
</div>

如果您觉得更简单,这是我的 CodePen ,具有相同的代码: https://codepen.io/fergos2/pen/bGGrqbr

0 个答案:

没有答案