zoukankan      html  css  js  c++  java
  • 多行文本框的字符数限制。

       在Web开发中经常会遇到多行文本框,比如:备注栏。普通的文本框控件如果想要限制字符长度可以直接设置maxLength属性,但是,一旦将文本框设置为多行,虽说也可以设置maxLength属性,但是我们会发现这个功能已经失效了,于是我找了个新的方法,比较复杂了点,希望大家有好的意见可以给我提。

    1.首先在<head></head>中添加下列js脚本:

    function setMaxLength(object,length) 

    var result = true
    var controlid = document.selection.createRange().parentElement().id; 
    var controlValue = document.selection.createRange().text; 
    if (controlid == object.id && controlValue != ""

    result 
    = true
    }
     
    else if (object.value.length >= length) 

    result 
    = false
    }
     
    if (window.event) 

    window.event.returnValue 
    = result; 
    return result; 
    }
     
    }
     

    //Check maxlength for multiline TextBox when paste 
    function limitPaste(object,length) 

    var tempLength = 0
    if(document.selection) 

    if(document.selection.createRange().parentElement().id == object.id) 

    tempLength 
    = document.selection.createRange().text.length; 
    }
     
    }
     
    var tempValue = window.clipboardData.getData("Text"); 
    tempLength 
    = object.value.length + tempValue.length - tempLength; 
    if (tempLength > length) 

    tempLength 
    -= length; 
    tempValue 
    = tempValue.substr(0,tempValue.length - tempLength); 
    window.clipboardData.setData(
    "Text", tempValue); 
    }
     

    window.event.returnValue 
    = true
    }
     

    2.在需要限制大小的文本框内添加下列属性:

     onkeypress="javascript:setMaxLength(this,100);" onpaste="limitPaste(this, 100)"

    其中的100是字符大小(注:汉字计入1个字符,100也就是指100个汉字或英文字母)

    有可能大家在.NET的服务器控件上添加以上代码时会提示说不含此属性,不用管它,直接运行就可以达到效果。

  • 相关阅读:

    python 爬取可用
    安装完出现Deprecated: Function ereg_replace() is deprecated in
    mysql数据库还原出错ERROR:Unknown command ‘\’解决手记
    mysql 常用语句
    This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery 解决方法
    js 中 json对象 与 json字符串 间相互转换
    神器 Sublime Text 3 的一些常用快捷键
    神器 Sublime Text 3 的一些常用插件
    apache php gzip压缩输出的实现方法
  • 原文地址:https://www.cnblogs.com/lovesangel/p/1288199.html
Copyright © 2011-2022 走看看