Reputation: 331
I made some jQuery that limits the character count in text fields. It works just fine, but any optimizations are welcomed. Now my issue is that if I want to apply this to multiple text fields, there is a conflict. The conflict is that when 1 character is entered into any text field, it affects all of the text fields specified in the jQuery.
jQuery
function countChar(val) {
var allowed_length = 20; // character count limit here
var len = val.value.length;
if (len >= allowed_length) {
val.value = val.value.substring(0, allowed_length);
jQuery('.chars-twenty').text(0);
} else {
jQuery('.chars-twenty').text(allowed_length - len);
}
}
countChar(jQuery('#demo1').get(0));
jQuery('#demo1').keyup(function() {
countChar(this);
})
countChar(jQuery('#demo2').get(0));
jQuery('#demo2').keyup(function() {
countChar(this);
})
I need the specific textarea character counts to act completely separate from one another.
Thank you so much.
Upvotes: 0
Views: 66
Reputation: 4194
var maxLen = 20; // character count limit here
function countChar(jqObj) {
var len = jqObj.val().length;
var diff = maxLen - len;
if (len > maxLen) {
len = maxLen;
diff = 0;
}
jqObj.val(jqObj.val().substr(0, len)).prev('p').find('span.chars-twenty').text(diff);
}
$(document).ready(function () {
$("[id*='demo']").keyup(function () {
countChar($(this));
}).each(function () {
countChar($(this));
});
});
Working fiddle forked and modified from OPs.
Upvotes: 0
Reputation: 6537
It's not really clean, but you could search for the class name in the prev() elements:
function countChar(val) {
var allowed_length = 20; // character count limit here
var len = val.value.length;
if (len >= allowed_length) {
val.value = val.value.substring(0, allowed_length);
// Notice the change here:
jQuery(val).prev().find(".chars-twenty").text(0);
} else {
// And here.
jQuery(val).prev().find(".chars-twenty").text(allowed_length - len);
}
}
countChar(jQuery('#demo1').get(0));
jQuery('#demo1').keyup(function() {
countChar(this);
})
countChar(jQuery('#demo2').get(0));
jQuery('#demo2').keyup(function() {
countChar(this);
})
Here's the updated Fiddle: http://jsfiddle.net/6vrhkkat/1/
Edit: Here's what I would do instead, assuming you are able to change the HTML. Add a data
attribute to the span to associate it with the particular textarea. This enables you to be sure of targeting the correct span, even if your DOM changes.
<span class="chars-twenty" data-textarea="demo1">
And then access the correct span using jQuery like this:
jQuery(".chars-twenty[data-textarea="+val.id+"]").text('...');
An example in another Fiddle: http://jsfiddle.net/6vrhkkat/2/
Upvotes: 1
Reputation: 4829
Depending on on what browsers you need to support, you might be able to simply use the maxlength
property. It is supported on Chrome, IE 10+, Firefox 4+, Opera 15+ and Safari.
<textarea rows="3" id="demo1" maxlength="20"></textarea>
Upvotes: 0