Learning Javascript and trying to learn how to pass values. In this example, I have a where a user types a message, for example, and that string is stored and displayed in a Bootstrap Modal. The problem…the last character is cut off unless you press return or spacebar. I have tried adding an empty space at the end of my document.getElementById (line 38)…tried adding a carriage return and new line….I have found several very simple Jquery solutions but it would be nice if I could figure this one out using JS first. Or maybe I should just switch the script to JQuery? I also know my character count isn’t working correctly but I’ll figure that out later.
Thanks!
//Write a function that shows how many characters are left in the textarea function charCount() { //Retrieve the stored value of the string from textarea var txt = document.getElementById("text-area").value; //Determine how many characters are in the textarea var chars = txt.length; //Subtract the max number of characters from the number of characters entered var maxLength = 140-chars; //Show how many characters remain in textarea document.getElementById("char-count").innerHTML = maxLength + " characters remaining"; //Write textarea string to modal document.getElementById("modal-body").innerHTML = txt + " "; }
<!-- Textarea --> <div class="row"> <div class="col-xl-12"> <textarea id="text-area" maxlength="140" onkeypress="charCount()"></textarea> </div> </div> <div class="row"> <div class="col-1"> <button class="btn btn-secondary d-inline" data-bs-toggle="modal" data-bs-target="#myModal">Submit</button> </div> <div class="col"> <div id="char-count"><!--140 Characters Remaining--></div> </div> </div> <div class="modal" id="myModal"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title">Your Message:</h4> <button type="button" class="btn-close" data-bs-dismiss="modal"></button> </div> <!-- Modal body --> <div class="modal-body" id="modal-body"> </div> <!-- Modal footer --> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div>
Advertisement
Answer
According to MDN (https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onkeypress), the onkeypress
event handler has been deprecated.
Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes
So, in order to avoid the cut of the last character, you can use the onkeyup
event handler, which fires when the user releases a key that was previously pressed.
<textarea id="text-area" maxlength="140" onkeyup="charCount()"></textarea>