I wrote a very simple script which attached a counter beside a textbox, and keeps track of the number of characters, updating on page load, and each time a character is entered.
My initial code, which works, is:
var text = ".new_description";
var monitor = text + "_monitor";
$(document).ready(function(){
if ($(text).val().length < 1) { $(monitor).css("color","black"); }
else if ($(text).val().length < 1001) { $(monitor).css("color","green"); }
else { $(monitor).css("color","red"); }
$(monitor).text( $(text).val().length + "/1000" );
$(text).keypress(function(event) {
window.setTimeout(function(){
if ($(text).val().length < 1) { $(monitor).css("color","black"); }
else if ($(text).val().length < 1001) { $(monitor).css("color","green"); }
else { $(monitor).css("color","red"); }
$(monitor).text( $(text).val().length + "/1000" );
}, 0);
});
});
I don't like that I have to duplicate the code that updates it, and I'd like to define the code, then just call it on page load, and then when a character is entered. I recreated the code using a function, and it worked:
$(function(){
var text = ".new_description";
var monitor = text + "_monitor";
$(document).ready(update_monitor);
$(document).ready(function(){
$(text).keypress(function(event) {
window.setTimeout(update_monitor, 0);
});
});
function update_monitor()
{
if ($(text).val().length < 1) { $(monitor).css("color","black"); }
else if ($(text).val().length < 1001) { $(monitor).css("color","green"); }
else { $(monitor).css("color","red"); }
$(monitor).text( $(text).val().length + "/1000" );
}
});
It only works if everything, including the call, is inside the $(function(){, and I'd like them to be separate. I read a little about making a plugin, but I wasn't able to get it to work. Is there any way to fully separate the defined sub function, and the main code inside the doc ready statement? Thanks for the help!