jquery 限制字数 显示输入字数 插件

时间:2020-12-21 16:10:21
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="artTxtCount.js"></script>
<style>
/* demo */
body { font-size:75%; font-family:'微软雅黑'; }
#demo { width:500px; }
#demo .help, #demo .help a { color:#999; }
#demo form { margin:20px 0; padding:8px; background:#F4F4F4; border:1px solid #EDEDED; }
#demo .tips { color:#999; padding:0 5px; }
#demo .tips strong { color:#1E9300; }
#demo .tips .js_txtFull strong { color:#F00; }
#demo textarea.text { width:474px; }
</style>
</head>
<script type="text/javascript">
$(document).ready(function(){
$(".autoTxtCount").each(function(){
$(this).find(".text").artTxtCount($(this).find('.tips'),120); });
$("#test").artTxtCount($("#test_tips"),10) });
</script>
<body>
<div id="demo">
<h1>artTxtCount - 轻量级输入字数提示插</h1>
<form class="autoTxtCount" action="" method="get">
<div>
<textarea class="text" name="" cols="50" rows="3"></textarea>
</div>
<div>
<button type="submit">提交</button>
<span class="tips"></span> </div>
</form>
<form class="autoTxtCount" action="" method="get">
<div>
<textarea class="text" name="" cols="50" rows="3"></textarea>
</div>
<div>
<button type="submit">提交</button>
<span class="tips"></span> </div>
</form>
<form action="" method="get">
<input class="text" id="test" name="" type="text" />
<span id="test_tips" class="tips"></span><br />
<button type="submit">提交</button>
</form>
</div>
</body>
</html>
以下是 artTxtCount.js
(function($){
$.fn.artTxtCount=function(tipWrap, maxNumber){
var countClass = 'js_txtCount', // 定义内部容器的CSS类名
fullClass = 'js_txtFull', // 定义超出字符的CSS类名
disabledClass = 'disabled'; // 定义不可用提交按钮CSS类名 var count=function(){ var btn=$(this).closest('form').find(':submit');
var val=$(this).val().length;
var disabled={
on:function(){
btn.removeAttr('disabled').removeClass("disabled");
},
off:function(){
btn.attr('disabled', 'disabled').addClass(disabledClass);
}
}
if (val==0) disabled.off();
if(val<=maxNumber){
if(val>0) disabled.on();
tipWrap.html('<span class="' + countClass + '">\u8FD8\u80FD\u8F93\u5165 <strong>' + (maxNumber - val) + '</strong> \u4E2A\u5B57</span>');
}
else{
disabled.off();
tipWrap.html(maxNumber - val);
}
}; $(this).bind('keyup change', count); return this; } })(jQuery);