sniker824 sniker824 - 5 months ago 10
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;
console.log(text);
var usedChars = text.length;
var remainingChars = maxChars - usedChars;
var message = "<p>" + remainingChars + "out of " + maxChars + " characters remaining </p>";
console.log(message);
$('#remaining').append(message);
}


$(document).ready( function () {

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

});


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 () {

$('#textArea').on("change",alert(1));

});


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

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

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

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

$('#remaining').html(message);