• 多行文本框的字符数限制。


       在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的服务器控件上添加以上代码时会提示说不含此属性,不用管它,直接运行就可以达到效果。

  • 相关阅读:
    HDU 3572 Task Schedule(拆点+最大流dinic)
    POJ 1236 Network of Schools(Tarjan缩点)
    HDU 3605 Escape(状压+最大流)
    HDU 1166 敌兵布阵(分块)
    Leetcode 223 Rectangle Area
    Leetcode 219 Contains Duplicate II STL
    Leetcode 36 Valid Sudoku
    Leetcode 88 Merge Sorted Array STL
    Leetcode 160 Intersection of Two Linked Lists 单向链表
    Leetcode 111 Minimum Depth of Binary Tree 二叉树
  • 原文地址:https://www.cnblogs.com/lovesangel/p/1288199.html
Copyright © 2020-2023  润新知