在textarea中限制每行的行数和字符数

时间:2016-08-12 18:34:23

标签: textarea

在查看了许多解决方案之后,我得到了以下完全符合我想要的解决方案。

解决方案1:除了在IE(11)中不起作用外,效果很好

如果有人可以帮我解决这个问题,我将非常感激。

代码取自:https://developer.mozilla.org/en-US/docs/Web/API/HTMLTextAreaElement

function checkRows(oField, oKeyEvent) {
  var nKey = (oKeyEvent || /* old IE */ window.event || /* check is not supported! */ { keyCode: 38 }).keyCode,

    // put here the maximum number of characters per line:
    nCols = 30,
    // put here the maximum number of lines:
    nRows = 5,

    nSelS = oField.selectionStart, nSelE = oField.selectionEnd,
    sVal = oField.value, nLen = sVal.length,

    nBackward = nSelS >= nCols ? nSelS - nCols : 0,
    nDeltaForw = sVal.substring(nBackward, nSelS).search(new RegExp("\\n(?!.{0," + String(nCols - 2) + "}\\n)")) + 1,
    nRowStart = nBackward + nDeltaForw,
    aReturns = (sVal.substring(0, nSelS) + sVal.substring(nSelE, sVal.length)).match(/\n/g),
    nRowEnd = nSelE + nRowStart + nCols - nSelS,
    sRow = sVal.substring(nRowStart, nSelS) + sVal.substring(nSelE, nRowEnd > nLen ? nLen : nRowEnd),
    bKeepCols = nKey === 13 || nLen + 1 < nCols || /\n/.test(sRow) || ((nRowStart === 0 || nDeltaForw > 0 || nKey > 0) && (sRow.length < nCols || (nKey > 0 && (nLen === nRowEnd || sVal.charAt(nRowEnd) === "\n"))));

  return (nKey !== 13 || (aReturns ? aReturns.length + 1 : 1) < nRows) && ((nKey > 32 && nKey < 41) || bKeepCols);
}
<form>
<p>Textarea with fixed number of characters per line:<br />
<textarea cols="50" rows="10" onkeypress="return checkRows(this, event);" onpaste="return false;" /></textarea></p>
</form>

解决方案2 它适用于IE,但在编辑行时失败。您键入一行,使用左箭头键返回并键入您可以键入1个字母,然后光标返回到结尾。 代码取自:http://cgodmer.com/?p=55

//limit # of lines of a text area and length of those lines
//<textarea rows="4" chars="40" onkeyup="limitTextareaLine(this, event)" ></textarea>
//Author: CGodmer (Feb 22, 2012)
function limitTextareaLine(x, e, nRows, nChars) {
 
    var rows = $(x).val().split("\n").length;   //number of rows
    var lineCharLimit = nChars;     //number of characters to limit each row to
    var rowLimit = nRows;           //number of rows to allow
 
    //limit length of lines
    for (var i = 0; i < rows; i++) {
        var rowLength = $(x).val().split("\n")[i].length;
 
        //check to see if any of the rows have a length greater than the limit
        if (rowLength > lineCharLimit) {
 
            //if it does save the beg index of the row
            var rowstartindex = $(x).val().indexOf($(x).val().split("\n")[i]);
 
            //use the index to get a new value w/ first lineCharLimit number of characters
            var newval = $(x).val().substring(0, rowstartindex + lineCharLimit)
                 + $(x).val().substring(rowstartindex + rowLength, $(x).val().length);
 
            //replace that value in the textarea
            $(x).val(newval);
 
            //set character position back to end of the modified row
            setCaretPosition($(x)[0], rowstartindex + lineCharLimit);
        }
    }
 
    //limit # of lines to limit to is rows attribute
    while($(x).val().split("\n").length > rowLimit) {
        $(x).val($(x).val().substring(0, $(x).val().length - $(x).val().split("\n")[rowLimit].length - 1));
    }
}
 
//Set caret position in the supplied control to position
//From: http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/
function setCaretPosition(ctrl, pos) {
    if (ctrl.setSelectionRange) {
        ctrl.focus();
        ctrl.setSelectionRange(pos, pos);
    }
    else if (ctrl.createTextRange) {
        var range = ctrl.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea rows="5" cols="10" onkeyup="limitTextareaLine(this, event, 5, 10)" ></textarea>

1 个答案:

答案 0 :(得分:0)

试试这个,它可以解决这个问题。

function ValidationAddress() {

             var allText;
             allText = document.getElementById("<%= txtAdd1.ClientID %>").value;
        allText = document.getElementById('<%=txtAdd1.ClientID%>').value;
         var A = allText.split('\n');
         var L = A.length;

         if (L > 3 && event.keyCode != 8 && event.keyCode != 46) {
             alert("You have exceeded maximum limit.Cannot insert more than 3 lines.");
             valert = false;
             return false;
         }
         var arr = allText.split("\n");
         for (var i = 0; i < arr.length; i++) {
             if (arr[i].length > 10) {

                 alert("You have exceeded the Maximum Limit..Characters per line is 70 in Address Field !");
                 valert = false;
                 return false;
             }
         }
     }