JSFiddle - React, Tailwind, and code Playground
counting remaining characters (in a textarea restricted by maxlength)
by jonchius
HTML
<div id="field1-counter">
<h1>welcome to field 1</h1>
<span id="field1-count"></span> character(s) remaining in field 1
</div>
<textarea id="field1" maxlength="140" rows="5" cols="28"></textarea>
<div id="field2-counter">
<h1>welcome to field 2</h1>
<span id="field2-count"></span> character(s) remaining in field 2
</div>
<textarea id="field2" maxlength="140" rows="5" cols="28"></textarea>
CSS
* {
font-family: Arial, Helvetica, sans-serif;
}
div {
padding-top: 1%;
}
JavaScript
// count characters for the first box
$("#field1-count").html($("#field1").attr("maxlength"));
$("#field1").on("keyup", { id: '#field1-count' }, countCharacters);
// count characters for the second box -- omg code reuse!
$("#field2-count").html($("#field2").attr("maxlength"));
$("#field2").on("keyup", { id: '#field2-count' }, countCharacters);
function countCharacters(event) {
var counterLabel = event.data.id;
var input = $(this).val().length;
var max = parseInt($(this).attr("maxlength"), 10);
$(counterLabel).html(max-input);
}