I insert Unicode-Smiley to HTML textarea. I have an second JS script to count characters typed by user to limit the length in the textarea, this is the JS code.
Now, when the Unicode smiley inserted with the first js code to the textarea, the second script dont show how many chars are inserted...the counter shows 0. I think the error is that the second js script need a line of code to watch when chars inserted via onclick, or the 2 scripts must merge to one?
function showEmoji(elem) {
document.querySelector('textarea').value += elem.textContent;
}
$(document).ready(function() {
$('textarea').on("input", function() {
var maxLength = $(this).attr("maxLength");
var currentLength = $(this).val().length;
var color = currentLength < 20 ? '#ff0000' : '#00BB00';
$('#minChars').css({
'color': color
});
$('#Chars').text(currentLength);
if (currentLength > 480) {
color = '#FF9900';
}
if (currentLength > 500) {
color = '#ff0000';
}
$('#Chars').css({
'color': color
});
});
});
<span onclick="showEmoji(this)">🤩</span>
<textarea name="text" rows="6" minlength="20" maxlength="500" required placeholder="Text.."></textarea>
<div><b id="Chars" class="red">0</b> from min. <b id="minChars" class="red">20</b> and max. <b class="red">500</b> Characters used.</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
You need to call your length update code on both events (icon append and text input). To do that, abstract that code into a new function and call it from both scenarios, passing in the jQuery object that is the textarea.
You can see how using jQuery for some parts of your code and not others can be a hassle. You have to get the raw element from the jQuery object to use some native JavaScript properties. See https://youmightnotneedjquery.com and consider converting to not require jQuery.
function updateLength(el) {
var maxLength = el.attr("maxLength");
var currentLength = el.val().length;
var color = currentLength < 20 ? '#ff0000' : '#00BB00';
$('#minChars').css({
'color': color
});
$('#Chars').text(currentLength);
if (currentLength > 480) {
color = '#FF9900';
}
if (currentLength > 500) {
color = '#ff0000';
}
$('#Chars').css({
'color': color
});
}
$(document).ready(function() {
$('textarea').on("input", function() {
updateLength($(this));
});
$('span').on('click', function() {
const textareaEl = $('textarea').first();
textareaEl[0].value += $(this)[0].textContent;
updateLength(textareaEl);
});
});
<span>🤩</span>
<textarea name="text" rows="6" minlength="20" maxlength="500" required placeholder="Text.."></textarea>
<div><b id="Chars" class="red">0</b> from min. <b id="minChars" class="red">20</b> and max. <b class="red">500</b> Characters used.</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>