第一种实现
jsp代码
<form action="" name="myForm">
<div class="pl_box"><textarea name="textarea" class="textarea_2"
disabled="" onKeyDown="textCounter(this.form.textarea,this.form.remLen,100);"
onKeyUp="textCounter(this.form.textarea,this.form.remLen,100);"></textarea>
</div>
<div id="showErrorDiv" style="font-size: 13px; color: red;">
您最多可以输入:<input name="remLen" type="text"
value="100" size="5" readonly="readonly" disabled="disabled">个字符
</div>
</form>
<div class="pl_btn"><a href="#" class="link1"
οnclick="publishComent('${username}')">发表评论</a></div>
js代码
function textCounter(field, countfield, maxlimit) {
// 函数,3个参数,表单名字,表单域元素名,限制字符;
if (field.value.length > maxlimit){
//如果元素区字符数大于最大字符数,按照最大字符数截断;
field.value = field.value.substring(0, maxlimit);
}
else
//在记数区文本框内显示剩余的字符数;
countfield.value = maxlimit - field.value.length;
}
第二种实现
jsp代码
<div class="pl_box">
<textarea name="textarea" class="textarea_2" disabled="" οnfοcus="fed_inputMaxLength(this,100,'catchask_con_counter_num')"></textarea>
</div>
<div class="textarea_con_counter">请发表您的观点评论内容,您还能输入<strong id="catchask_con_counter_num" class="catchask_con_counter_num" >100</strong>字。
<span id="textareaError" class="textarea_con_textareaError"></span>
</div>
js代码:
function fed_inputMaxLength(target,maxlength,counterId){
if($(target).attr('fed_max_length')==null){
$(target).attr('fed_max_length',maxlength);
var counter = $('#'+counterId);
if ($.browser.msie) { //IE
$(target).unbind("propertychange").bind("propertychange", function(e) {
e.preventDefault();
textareaMaxProc1(target, maxlength);
counter.html(maxlength-$(target).val().length);
});
target.attachEvent("onpropertychange", function(e) {
//e.preventDefault();
textareaMaxProc1(target, maxlength);
counter.html(maxlength-$(target).val().length);
});
}else {
target.addEventListener("input",function(e) {
e.preventDefault();
textareaMaxProc1(target, maxlength);
counter.html(maxlength-$(target).val().length);
},false);
}
$('target').unbind("keypress").bind("keypress", function(event) {
var code;
if(typeof event.charCode =="number" ){
code = event.charCode;
}else{
code = event.keyCode;
}
if(code > 9 && !event.ctrlKey && $(target).val().length>=maxlength){
event.preventDefault();
}else if(event.ctrlKey && $(target).val().length>=maxlength && code==118){
event.preventDefault();
}
});
}
}
function textareaMaxProc1(textArea, total){
var max;
max=total;
if($(textArea).val().length > max){
$(textArea).val($(textArea).val().substring(0,max));
}
}