I’m not sure if the title is correct. I can’t seem to express this problem properly in words!
I have the following text fields in my HTML that I’m trying to limit the number of characters that can be entered into:
<div class="limited limit-200">
<div class="label">
<label for="_je_industries_desc">Industry Description</label>
</div>
<div class="input">
<textarea class="large-text" name="industries_desc" id="industries_desc" cols="60" rows="3"></textarea>
<p id="industries_desc_description" class="description">Put a short description of this industry.</p>
</div>
</div>
<div class="limited limit-100">
<div class="label">
<label for="_je_seo_description">Meta Description</label>
</div>
<div class="input">
<textarea class="large-text" name="seo_description" id="seo_description" cols="60" rows="3"></textarea>
<p id="seo_description_description" class="description">Put a short description of the content of this page.</p>
</div>
</div>
Here’s my jQuery so far.
It gets the character limit from the class name in the HTML limit-200 for example. Then calculates the amount of characters left as you type and outputs the remaining characters under the textarea.
jQuery(document).ready(function(){
jQuery('.limited').each(function() {
// Get the class names of any element that has the class .limited
var className = jQuery(this).attr('class');
// Use regex to capture the character limit class (limit-#)
var limit = className.match(/[?:limit-](\d+)/);
// Set the limit var to the match from the regex
var limit = limit[1];
// Calculate the number of characters that are still available (limit - characters in field)
var chars_left = limit - jQuery('textarea', this).val().length;
//alert(chars_left);
// Attach an event handler to each textarea with the class .limited
jQuery('textarea', this).on('keyup', function() {
var maxchar = limit;
var cnt = jQuery(this).val().length;
var remainingchar = maxchar - cnt;
if(remainingchar < 0){
jQuery('#limit-counter span').html('<strong>0</strong>');
jQuery(this).val(jQuery(this).val().slice(0, limit));
} else {
jQuery('#limit-counter span').html('<strong>' + remainingchar + '</strong>');
}
});
// Display number of characters left
jQuery('textarea', this).after('<span id="limit-counter">Remaining characters: <span><strong>' + chars_left + '</strong></span></span>');
});
});
This works great for a single textarea but if I have more than one and type in one of the textareas the other textarea updates its counter with the same value as the one I’m typing in.
Could someone please help me spot what I’m doing wrong? Hopefully I’m just missing something simple somewhere!
Thanks!
I’ve added this to a fiddle and done the modifications:
http://jsfiddle.net/KQKnN/
Trouble here that your limit-counter has to be unique, you can’t have two elements with the same id on one page.
I also added the textarea to a cached selector – you’ll get better performance because of this but it’s totally optional.