Ad

Execute JQuery Function When The Page Is Loaded Instead On .keyup

- 1 answer

I have a function that look like that

var text_max = 200;
$('#count_message').html('0 / ' + text_max );

$('#text').keyup(function() {
  var text_length = $('#text').val().length;
  var text_remaining = text_max - text_length;

  $('#count_message').html(text_length + ' / ' + text_max);
});

And what I am trying to achieve is it to be executed immediately after the page is loaded, meaning that it counts the text length for the already existing text in the textarea and not after you type something.

I have tried putting it in a function like that

function myFunction() {

var text_max = 200;
$('#count_message').html('0 / ' + text_max );

$('#text').keyup(function() {
  var text_length = $('#text').val().length;
  var text_remaining = text_max - text_length;

  $('#count_message').html(text_length + ' / ' + text_max);
});

}

And then executing it in the body like that

<body onload="myFunction()">

But I am not doing something right or maybe that's not the way to do it. I have my suspicions that I have to do something within the .keyup(function() and not just loading it in the body but not really sure what to do. I have tried to find something in the jQuery Event Methods that I can use but couldn't find anything that works. Also, tried some ideas I found here but it did not work either.

Here is where I got the original script from https://www.codeply.com/go/s0F9Iz38yn/bootstrap-textarea-with-character-count-_-bootstrap-3

EDIT I want to keep the .keyup functionality but also to count when the page is loaded

Ad

Answer

Remove the keyup outside from the function and call it on load like,

var text_max = 200;
function myFunction($txt) {
   var text_length = $txt.val().length;
   var text_remaining = text_max - text_length;
   $('#count_message').html(text_length + ' / ' + text_max);    
}
$(function(){
   $('#text').keyup(function(){
       myFunction($(this));
   });
   myFunction($('#text'));
});
Ad
source: stackoverflow.com
Ad