How can I make my character counter display how many characters are left on page load. Right now it only displayed the number of characters left when I user keysup, keysdown or onblurs.
var companydo = document.getElementById('cscompanydo');
function validate_companydo_field_length() {
var len = companydo.value.length;
var mc = 2000;
if (len > mc) {
companydo.value = companydo.value.substring(0,mc);
len = mc;
}
document.getElementById('doremaining').innerHTML = mc - len;
}
companydo.onkeyup = validate_companydo_field_length;
companydo.onkeydown = validate_companydo_field_length;
companydo.onblur = validate_companydo_field_length;
<textarea class="medium mediumwidth man" id="cscompanydo" name="companydo" rows="" cols=""><?php echo $answer['companydo']; ?></textarea>
<div class="f_right mts mrs"><span id="doremaining" class="mrs">2000</span>characters remaining</div>
If you put the script at the end of the body (which is where scripts should be, just before the </body> tag), you can then trigger one of the events manually with:
companydo.onkeyup();
Yes, but I want the character count displayed when the page loads. It defaults to 2000 before anyone types anything. It also will show 2000 even if text is currently in the textarea so long as you haven’t typed in it yet.
You are misinterpreting what I said. Putting script commands at the end of the body allows you to run script command before the page load event occurs.
Let me try and get this idea across to you in a different way.
You need to run the script that updates the character count when the page loads. That means you need to run a script that triggers the update.
You have already attached an onkeyup event to the companydo element with the following command:
companydo.onkeyup = validate_companydo_field_length;
So you now need to trigger that onkeyup event when the page loads, which will allow the counter number to be updated.
The code you need to add in order to trigger that onkeyup event is:
companydo.onkeyup();
Whether you run that triggering script from an onload event, or from the end of the body just before the </body> tag, or in some other way, it is the act of running that additional line of code that allows the character count to update.
I advise that you add that line of code to your script, and that you load your script from the end of the body.
Best practices: Put scripts at bottom
script.js
var companydo = document.getElementById('cscompanydo');
// other code ...
companydo.onkeyup = validate_companydo_field_length;
companydo.onkeydown = validate_companydo_field_length;
companydo.onblur = validate_companydo_field_length;
companydo.onkeyup();
<body>
<!-- form stuff here -->
<script type="text/javascript" src="script.js">
</body>
</html>