Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ilya_user's avatar

Counting characters during edit

I have a script that is used to count the number of characters in the input. It works well for the creation, but when it comes to the edit form the problem is that while displaying the old input it shows 0 and only starts counting when I'm starting to add some characters to the input. So I need it to display the number of characters of the old input even if I didn't add any new characters yet. How can I achieve that? HTML code:

<input type="text" name="name" class="form-control" value="{{ $employee->name }}" placeholder="Name is..." id="myText">
<div class="d-flex justify-content-end">
<span id="wordCount" class="text-muted">0</span>
<span class="text-muted">/</span>
<span class="text-muted">256</span>
</div>

Script:

var myText = document.getElementById("myText");
var wordCount = document.getElementById("wordCount");

myText.addEventListener("keyup",function(){
        var characters = myText.value.split('');
        wordCount.innerText = characters.filter( item => {
            return (item != ' ');
        }).length;
});

0 likes
1 reply
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Move it to a function and call it when the page loads as well

function countChars() {
        var characters = myText.value.split('');
        wordCount.innerText = characters.filter( item => {
            return (item != ' ');
        }).length;
]

myText.addEventListener("keyup",function(){
    countChars()
});
countChars()
1 like

Please or to participate in this conversation.