遍历页面所有textarea框,限制其内容不能超过字符(jquery版)

遍历网页中所有textarea,如果超过数字就弹出提示并折断.

    

//限制输入框字符

    $(document).ready(function(){
  var tempval,leng=300; //默认输入的字符数
        $("textarea").each(function(){
                    if($(this).className!=null){
                        if(!isNaN($(this).className.substring($(this).className.length-3,$(this).className.length))){
                            leng=$(this).className.substring($(this).className.length-3,temp.length);
                        }
                    }
                      
                 
                    $(this).mouseover(function(e){
                        $(this).next().css({display:"block"});
                    }).mouseout(function(e){
                        $(this).next().css({display:"none"}); 
                    }).keyup(function(e){
if(parseInt(leng-GetCharLength($(this).attr("value")))>=0){
                       $(this).next().html("还可以输入:"+parseInt(leng-GetCharLength($(this).attr("value")))+",共:"+leng+"个字");
}else{
                       $(this).next().html("对不起你已经输入250个字了");
}
                    }).after("<nobr class=\"allinputtip\">你一共能输入"+leng+"个字</nobr>").mousemove(function(e){
                    $(this).next().css({left:e.pageX-($("body").width()/2-454),top:e.pageY-106});    //修改提示框的位置
}).change(function(){
                    //$(this).next().html("您还能输入"+leng-GetCharLength($(this).attr("value")));
                     tempval=$(this).attr("value");
                         for(var i=0;i<leng;i++)
                         {
                         if(GetCharLength(tempval)<leng){                         
                          $(this).attr("value",tempval.substr(0,i+1));
                         }
                         else
                         {
                         break;}
                         }
                         if(GetCharLength($(this).attr("value"))>leng){
                         //
                         $.prompt("字符不能超过"+leng+"个,汉字不能超过"+leng/2+"个"); // 调用的提示插件
                             for(var k=GetCharLength($(this).attr("value"));k>leng;k--){
                             if(GetCharLength($(this).attr("value"))>leng)
                              $(this).attr("value",tempval.substr(0,$(this).attr("value").length-1));
                             }
                         }                       
                    })
        })
    
     })
     
     function GetCharLength(str)
    {
     var iLength = 0;
     for(var i = 0;i<str.length;i++)
     {
     if(str.charCodeAt(i) >255)
     {
     iLength += 2;
     }
     else
     {
     iLength += 1;
     }
     }
     return iLength;
    }
posted on 2008-07-31 10:52  sin  阅读(1016)  评论(0)    收藏  举报

阳江人才网