Execute JQuery Function When The Page Is Loaded Instead On .keyup
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
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'));
});
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM