Character Counter & Limiter - code clarity
I wrote small character counter & limiter.
You can test it here: Char Counter & LimiterjQuery Code:
$(document).ready(function() {
$('.counter').each(function(index) {
$('.counter p span').html('0'); // set character length to 0
$('input', this).keyup(func开发者_如何学Ction() {
var CounterDiv = $(this).parent(); //
var Limit = $('p', CounterDiv).html().split(' / ')[1];
var CurrentLength = $(this).val().length;
if (CurrentLength == Limit) {
$('p span', CounterDiv).html(CurrentLength);
return false;
} else if (CurrentLength > Limit) {
var str = $(this).val();
$(this).val(str.substring(0, str.length - 1));
return false;
} else {
$('p span', CounterDiv).html(CurrentLength);
}
});
});
});
Have you got any suggestion how can I improve that? I'm not 100% sure with the syntax.
Use native html maxlength
attribute for inputs
here is the sample: http://jsfiddle.net/8YdCh/16/
html
<input name="input1" type="text" maxlength="8" />
js
$(document).ready(function() {
$('.counter').each(function(index) {
$('.counter p span').html('0'); // set character length to 0
$('input', this).keyup(function() {
var $countSpan = $(this).parent().find('.var-count'); // find the count span
var countValue = $(this).val().length + " / " + $(this).attr('maxlength'); // format value for count span 'current value lenght / maxlength attribute'
$countSpan.text(countValue); // set formatted value to your column span
});
});
});
精彩评论