I'm having an issue with a character count function on a form textarea
. There are a host of solutions available on the web and I've come across a very handy snippet shown below which will output the number of characters left in the specified area on the page:
var maxLength = 1000;
jQuery('.your-enquiry').keyup(function() {
var length = jQuery(this).val().length;
var length = maxLength-length;
console.log(length + "characters remaining");
jQuery('#counter').text(length);
});
You can see that I am outputting the length variable
to the console window in a bid to see what my problem is. It seems that as soon as I release a key length is assigned a value of X and then immediately assigned 1000 again.
Here is an example of my output:
995characters remaining (index):542
1000characters remaining (index):542
When I check line 542 of my code it is:
console.log(length + "characters remaining");
How come length is being output twice every time!? and effectively resetting itself? Am I using the wrong type of event on the textarea? Ideally I'd like the counter to update in real time as the user types.
Some side information if it's helpful...
I am using Contact Form 7 version 4.5.1
to create the form. My HTML
output looks like this:
<div>
<span class="wpcf7-form-control-wrap your-enquiry">
<textarea name="your-enquiry" cols="40" rows="10" maxlength="1000" minlength="10" class="wpcf7-form-control wpcf7-textarea wpcf7-validates-as-required your-enquiry" aria-required="true" aria-invalid="false"></textarea></span>
<p id="counter">1000</p>
</div>
NOTE: Just did a quick bit of research on the keyUp
event and apparently it is triggered every time a Key is released. Which makes sense but confuses me as my value is being output twice.