I would like to obtain the character count of two textareas with different maxlengths. However, I believe I am having some conflicts with their ids (used to achieve their different maxlengths of 50 and 100).
The jQuery code works fine when only used for one textarea by adapting its classes and id. However, it does not work at all for two when I use
var myText = document.querySelectorAll('#myTextOne, #myTextTwo').maxLength;
NOT A DUPLICATE: someone asked a similar question in Perform character count on different textarea id . However, they used the same maxlength for all textareas which is not my case. I am using the textareas' ids to obtain their particular wordcounts.
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>
If you find it easier, here's my CodePen with the same code: https://codepen.io/fergos2/pen/bGGrqbr