I am trying to add a character counter / indicator for a smart multiline textbox control. I want to update my character counter as the user is typing in the text box. What is the best way to accomplish this? I have tried adding an event handler with the ‘input’ event, as well as the change event listed in the API.
Both of these events seem to work partially, however when I try to access the current value of the multiline textbox, it does not seem to update with the actual current input until after the control loses focus. What is the best way to accomplish this and see the current value as it is being entered?
Here is my current test code using the input event (which does fire with each keystroke – but the length value is incorrect until the texbox focus is lost):
<p>Add a concise statement (150 or fewer characters):</p>
<smart-multiline-text-box id=”addStatementTextbox” auto-focus placeholder=”” max-length=”150″ style=”width: 500px; height: 100px;”></smart-multiline-text-box>
<div class=”characterCounter” id=”statementCharacterCounter”> 0 / 150 characters</div>
<script type=”text/javascript”>
(function (generateUI, $, undefined) {
generateUI.addStatementTextbox = document.getElementById(‘addStatementTextbox’);
generateUI.init = function () {
generateUI.addStatementTextbox.addEventListener(“input”, ({ currentTarget: target }) => {
console.log(“addStatementTextbox.addEventListener input”);
console.log(“target.value: ” + target.value);
let currentLength = target.value.length;
console.log(“currentLength: ” + currentLength);
});
};