function limitCharsNum(charsNumSpanId,id,max) { setTimeout(function(){ var valLen=$("#"+id).val().length; console.log(max); if(valLen>max) { console.log(valLen); $("#"+id).val($("#"+id).val().substring(0,max)); } $("#"+charsNumSpanId).text((max-valLen)<=0?0:(max-valLen)); }, 100); } function initLimitCharsNum(charsNumSpanId,id,max) { $("#"+id).attr("onpaste","limitCharsNum('"+charsNumSpanId+"','"+id+"',"+max+")"); $("#"+id).attr("oncut","limitCharsNum('"+charsNumSpanId+"','"+id+"',"+max+")"); $("#"+id).attr("onkeydown","limitCharsNum('"+charsNumSpanId+"','"+id+"',"+max+")"); $("#"+id).attr("onkeyup","limitCharsNum('"+charsNumSpanId+"','"+id+"',"+max+")"); $("#"+id).attr("ondrop","limitCharsNum('"+charsNumSpanId+"','"+id+"',"+max+")"); }
例子:
initLimitCharsNum('remainderNum1','ztinput1',100);
initLimitCharsNum('remainderNum2','fsnrtextarea1',100);