简体   繁体   中英

Count characters in textfield on keydown event

I want to live update the amount of characters entered in a textfield as the user puts them in. I am not getting too far. This is what I have so far. It changes to zero. I'm rather new to javascript to a beginner explanation would be great.

 function doThis() { x = document.getElementById("area").textContent; y = x.length; document.getElementById("demo").innerHTML = y; } 
 <textarea id="area" onkeydown="doThis()"></textarea> <p id="demo">Count goes here</p> 

To get the content of the textarea use .value and change the event to onkeyup .

 function doThis() { x = document.getElementById("area").value; y = x.length; document.getElementById("demo").innerHTML = y; } 
 <textarea id="area" onkeyup="doThis()"></textarea> <p id="demo">Count goes here</p> 

instead of textcontent use value and if you want to use keydown, add +1

 function doThis() { x = document.getElementById("area").value; y = x.length + 1; document.getElementById("demo").innerHTML = y; } 
 <textarea id="area" onkeydown="doThis()"></textarea> <p id="demo">Count goes here</p> 

note: if you copy and paste it will give you wrong result, so better to use onkeyup

Alternative answer with .querySelector() and less code:

 document.querySelector('#area').onkeyup = function() { document.querySelector('#demo').innerHTML = this.value.length; } 
 <textarea id="area"></textarea> <p id="demo">Count goes here</p> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM