Limit all textarea to specified number of characters
On the page there are number of text area. The number is dynamic not fixed. I need to limit length of all text areas on one page. How can I do this in js or jquery?
My try:-
<body>
<div id="contact">
<form action="" method="post">
<fieldset>
<table style="width: 100%;">
<tr class="questionsView" style="width: 100%;margin: 5px;">
<td class="mandatory">
<b>1
*Qywerew we</b>
<hr/>
<table class="profileTable" style="margin-left: 25px;">
<tr>
<td>
<textarea style="border: solid 1px #800000;" rows="5" name="165" cols="100">
</textarea>
</td>
开发者_C百科 </tr>
</table>
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr class="questionsView" style="width: 100%;margin: 5px;">
<td class="">
<b>2
a da da da</b>
<hr/>
<table class="profileTable" style="margin-left: 25px;">
<tr>
<td>
<textarea style="border: solid 1px #800000;" rows="5" name="166" cols="100">
</textarea>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
<input type="submit" value="Submit" onclick="return checkThis()">
</fieldset>
</form>
</div>
<script>
$('textarea').bind('paste keyup blur', function(){
$(this).val(function(i, val){
return val.substr(0, 5);
});
});
</script>
</body>
$('textarea').bind('paste keyup blur', function() {
$(this).val(function(i, val) {
return val.substr(0, 5);
});
});
jsFiddle.
Update
I don't know why but it prints
function(i, val) { return val.substr(0, 5); }
in text area every time.
Sounds like you are using an older version of jQuery (pre 1.4
). The refactored code below will work.
$('textarea').bind('paste keyup blur', function() {
$(this).val(this.value.substr(0, 5));
});
jsFiddle.
The previous code would not work prior to jQuery 1.4 because it expected a string only as the argument to val()
. By passing a function, its toString()
was implicitly called, returning the string representation of the function.
Horrible and aggressive way
setInterval(function(){
$('textarea').each(function(){
if (this.value.length > 5){
this.value = this.value.substr(0,5);
}
})
}, 1)
http://jsfiddle.net/YMsEF/
var maxLettersCount = 3;
$('textarea').bind('keydown paste', function(event) {
var textarea = $(event.target),
text = textarea.val(),
exceptionList = {
8: true,
37: true,
38: true,
39: true,
40: true,
46: true
};
if (event.type == 'keydown' && text.length >= maxLettersCount && !exceptionList[event.keyCode]) {
return false;
} else if (event.type == 'paste') {
setTimeout(function() {
textarea.val(textarea.val().substring(0, maxLettersCount));
}, 1);
}
})
精彩评论