I am new to JavaScript and I am trying to add a character counter to a text field using this code:
$(function(){
$('.txtclass').keypress(function(){
ta = $(this);
if(ta.val().length >= 350){
ta.val( ta.val().substr(0, 350) );
} else {
$("#counter span").text(350-ta.val().length);
}
});
});
setInterval('$("#counter span").text(350-ta.val().length);', 350);
I get that JavaScript error: "Error: ta is not defined" and points me to that specific line in my code.
Any insight into whats happening and how to fix it would be really appreciated as I’d like to add more counters for other text-fields into the website elsewhere.
Edit: here’s the html for the counter
<div id="counter"><span>350</span> characters remaining.</div>
</div>
It means just what it says. The value being passed to the
textmethod is the result of the expression350 - ta.va().length. The variabletahas not been defined at the point this code is being run.A few things to note before my proposed solution.
setIntervalin quotes. This causes it to be run througheval, which is both slower and less secure.Here’s how I would implement this: