sniker824 sniker824 - 1 year ago 42
jQuery Question

javascript on change needs refresh

I'm trying to make a textbox, with a counter to show how many signs you have left (pure for user interface purposes, not the actual validation).

I tried to use this code:

function checkRemainingChars () {

var maxChars = 500;
var text = document.getElementById('textArea').value;
var usedChars = text.length;
var remainingChars = maxChars - usedChars;
var message = "<p>" + remainingChars + "out of " + maxChars + " characters remaining </p>";

$(document).ready( function () {



where #textArea is the textarea where the user puts his text, and #remaining is an aside with the message how much signs he has remaining.

this only works when the page loads/refreshes. then I tried to add something simple, to eliminate possible mistakes in my code:

$(document).ready( function () {



but even here I only get the alert when I refresh the page. What do I have to do to make the text update as soon as the user types something?

Answer Source

You are calling the method and assigning what it returns to the event listener, not assigning a reference to the method.


drop the ()

$('#textArea').on('change', checkRemainingChars);

If you need the method to run when the page loads, you can trigger the change event.

$('#textArea').on('change', checkRemainingChars).trigger("change");

or you can call change directly.

And finally you are appending messages to the element for what is remaining. I do not think you want append, you probably want to use