Home > OS >  How to count the number of characters inside <input> tag HTML with JS
How to count the number of characters inside <input> tag HTML with JS

Time:09-11

i'm trying to create a function that count the characters inside a input tag of a signup form.

document.getElementById('username').onkeyup = function() {
  document.getElementById('caratteriRimanentiUsername').innerText = "Caratteri: "   this.value.length   "/30";
};
<div >
  <span >Username</span>
  <input id="username" type="text" name="username" placeholder="Inserisci il tuo username">
  <span id="caratteriRimanentiUsername">Caratteri: 0/30</span>
</div>

Inside the JS file there are other functions that use onkeyup can that be a problem?

Error from Console Browser

CodePudding user response:

I don't think that is the correct syntax to add an event listener to a node. Also, make sure the DOM is loaded and parsed before you add the listener.

I think the following code should do what you want (provided that the DOM node exists and has been parsed):

const input = document.getElementById('username');
const characterCountDisplay = document.getElementById('caratteriRimanentiUsername')
let inputLength = 0;

input.addEventListener('keyup', event => {
    inputLength = event.target.value.length
    characterCountDisplay.textContent = `Caratteri: ${inputLength}/30`
})

CodePudding user response:

To clarify your question regarding .onkeyup:

It can indeed be a problem if used again on the same element:

element.onkeyup will overwrite previously assigned .onkeyup (or even inline element onkeyup="" event handlers.

element.addEventListener('keyup', yourFunction) is usually the preferred way, as it lets you add multiple eventListeners to the same element (and remove.addEventListener still lets you remove them if needed) .

CodePudding user response:

Maybe you need to place your script after the element.

<div >
  <span >Username</span>
  <input id="username" type="text" name="username" placeholder="Inserisci il tuo username">
  <span id="caratteriRimanentiUsername">Caratteri: 0/30</span>
</div>

<script>
document.getElementById('username').onkeyup = function() {
  document.getElementById('caratteriRimanentiUsername').innerText = "Caratteri: "   this.value.length   "/30";
};
</script>
  • Related