如何将文本区域中每行的字符数限制为固定值

时间:2011-03-08 17:43:05

标签: javascript asp.net-mvc

在我的文字区域,我应该每行只能输入72个字符。如果我使用cols属性设置为72,则根据字符宽度允许更多或更少的字符数。

任何人都可以帮忙怎么做吗?

11 个答案:

答案 0 :(得分:5)

重复Textarea Limit characters per line Jquery or Javascript

<TEXTAREA NAME="HARD" COLS="72" ROWS="5" WRAP="HARD">

答案 1 :(得分:4)

我遇到了同样的问题并试图用JavaScript解决它。为什么不采用Juan Mendes建议的HTML代码?

嗯,这很简单:它在浏览器中不起作用,或者至少在Ubuntu下使用Firefox 25,每行的最大字符数似乎受到textarea宽度的限制,并且取决于我可以输入的字体大小+ -1个字母。但我希望每行的字符数限制为特定值,无论textarea的宽度是多少。所以我提出了这个代码:

var maxLength = 3;
$('#mytext').on('input focus keydown keyup', function() {
    var text = $(this).val();
    var lines = text.split(/(\r\n|\n|\r)/gm); 
    for (var i = 0; i < lines.length; i++) {
        if (lines[i].length > maxLength) {
            lines[i] = lines[i].substring(0, maxLength);
        }
    }
    $(this).val(lines.join(''));
});

我还准备了jsFiddle。我希望这有助于某人:)

最后只是对此代码如何工作的简短解释:

  • 该函数等待以下事件之一:输入,焦点,keydown,keyup(使用这么多事件可能看起来有点不必要,但我经常测试找到这个组合,它可以工作crossbrowser并且总是触发,无论如何如果只输入单个字母,则会持续按下该键或将文本粘贴到textarea)
  • 它获取textarea的值
  • 然后它将每个换行符处的textarea拆分为一个新的数组元素
  • for循环遍历此数组并分别检查数组的每一行元素,如果它超过之前设置的maxLength
  • 如果一行超过maxLength,则该行在maxLength字符后被“切断”
  • 最后,当没有剩余的行超过maxLength个字符时,数组元素再次以字符串形式连接在一起
编辑:我现在发现的唯一限制是,当在开头或行内输入一个额外的字符时,代码“切断”字符串的末尾而不是字符的添加位置。这在大多数情况下无关紧要,但请记住:)无论如何,适当地更改此功能应该不会太困难,但在大多数情况下,这将浪费资源;)

答案 2 :(得分:2)

完成先前解决方案的一小部分内容 我也限制了行数。

它在旧系统中为我提供服务,在4个数据库条目中保存4行注释。

<textarea id="mytext" rows = "4" style="width:300px"></textarea>

$(function() {

    var maxLength = 30;
    var mawRow = 4;

    $('#mytext').on('input focus keydown keyup', function() {

        //get Textearea text
        var text = $(this).val();

        //Split with \n carriage return
        var lines = text.split("\n"); 

        for (var i = 0; i < lines.length; i++) {
            if (lines[i].length > maxLength) {
                lines[i] = lines[i].substring(0, maxLength);
            }     
        }

        //On supprime ce qui dépasse... :)
        while (lines.length > 4){    
            lines.pop();
        }

        //Join with \n.
        //Set textarea
        $(this).val(lines.join("\n"));
    });
});

答案 3 :(得分:1)

这是一种限制每行字符数和行数的文本区域的方法。为了使输入交互对用户来说很直观,它需要处理(1)输入的值(2)光标位置

  1. (a)从文本区域读取值,(b)根据长度限制的要求检测每行文本是否太长,(c)从一行到下一行推入超文本,以及(d)返回写值到文本区域。
  2. (a)读取CURSOR POSITION以存储光标位置,以及(b)POSITION CURSOR WRITE DATA后用户期望的光标位置。

在此处查看代码笔: https://codepen.io/MattWritingCode/pen/bmexwa

这是必不可少的javascript代码(已在Safari和Chrome上测试过,将文本粘贴到textarea时也可以正常工作):

var charactersPerLine=document.getElementById("charactersPerLine").value;
var maxLines=document.getElementById("maxLines").value;
var textOutput="";
var onPaste=false;

function formatTextAsRequired() {
  /*
  This function handles two aspects:
  1. (a) READ VALUE from the textarea, (b) DETECT IF TEXT PER LINE IS TOO LONG  as required by the length restrictions, (c) PUSH OVERFLOWING TEXT from a line to the next line and (d) WRITE VALUE back to the textarea.
  2. (a) READ THE CURSOR POSITION to store the cursor position, and (b) POSITION THE CURSOR where a user would expect it after WRITE DATA.
  */
  var textInput=document.getElementById("flexibleInputField").value;//1a: READ VALUE
  var inputAsRows=textInput.split("\n");// create array from input => each element contains one row of the textarea
  var inputAsOneLine=textInput.replace(/(\r\n\t|\n|\r\t)/gm,"");//remove all line-breaks
  var cursorPositionOnInput=document.getElementById("flexibleInputField").selectionStart;//2a: READ CURSOR POSITION
  var cursorOffsetAfterOutput=0;//set default value for cursor offset. cursor offset is needed when re-posiotioning the cursor after WRITE DATA

  var totalRows=inputAsRows.length; //don't put inputAsRows.length in the for statement, as the array is growing in the loop which results in an infinite loop
  var row;
  var lineBreakCount=0;
  var characterCount=0;
  for (row = 0; row < totalRows; ++row) {
    if(inputAsRows[row].length>charactersPerLine){ //1b DETECT IF TEXT PER LINE IS TOO LONG 
      if (inputAsRows[row+1] === undefined) {
        inputAsRows[row+1]="";// the row did not exist
        totalRows++;
        }
      //1c PUSH OVERFLOWING TEXT: move text that is too long for this row to the next row:
      inputAsRows[row+1]=inputAsRows[row].substring(charactersPerLine)+inputAsRows[row+1];
      inputAsRows[row]=inputAsRows[row].substring(0,charactersPerLine);
      //determine, if cursor was at the end of the line that got a line-break:
      var newOutput=inputAsRows.join("\n");
      if(newOutput.substr(cursorPositionOnInput-1,1)=="\n"){
        cursorOffsetAfterOutput=1; }
      }
    }

  if(inputAsRows.length<=maxLines && inputAsOneLine.length<=(maxLines*charactersPerLine)){//data is within max number of rows and max total digits
    textOutput=inputAsRows.join("\n");
    document.getElementById("flexibleInputField").rows=inputAsRows.length;//resize textarea
    document.getElementById("errors").innerHTML="";//remove error message
    document.getElementById("count").innerHTML=inputAsOneLine.length+"/"+(maxLines*charactersPerLine);//show digits count
    if(onPaste){ cursorOffsetAfterOutput=cursorOffsetOnPaste(textInput,cursorPositionOnInput,totalRows)
      }
    }
    else //data would be too long 
    {
    document.getElementById("errors").innerHTML="This field can only have "+maxLines+" lines with "+charactersPerLine+" characters per line.";//display error message
    document.getElementById("count").innerHTML="";//remove digits count
    cursorOffsetAfterOutput=-1;
  }
  document.getElementById("flexibleInputField").value=textOutput;//1d: WRITE VALUE
  document.getElementById("flexibleInputField").selectionStart=cursorPositionOnInput+cursorOffsetAfterOutput; //2b: POSITION CURSOR
  document.getElementById("flexibleInputField").selectionEnd=cursorPositionOnInput+cursorOffsetAfterOutput; //set a single cursor, not a selection
  onPaste=false;
}

function countLineBreaks(string,lengthFromStart){
  var left=string.substr(0,lengthFromStart);
  var countOfLinebreaks=(left.split("\n")).length;
  return countOfLinebreaks;
}

function handlePaste(){
  //some improvements when pasting content can still be made (particularly on the cursor position)
  onPaste=true;
}

function cursorOffsetOnPaste(textInput,cursorPositionOnInput,totalRows){
  //offset the cursor by 1 for each added line break:
  var countOld=countLineBreaks(textInput,cursorPositionOnInput);  
  var countNew=countLineBreaks(textOutput,cursorPositionOnInput+totalRows);
  cursorOffsetAfterOutput=countNew-countOld;
  return cursorOffsetAfterOutput;
}

答案 4 :(得分:0)

我会在每次有一个onkeypress事件时检查当前行长度是什么,然后在超过72时在最近的前一个空格处插入一个break。如果用户粘贴一个文本块,则会遇到困难。那么,你必须检查前一个光标位置和新光标位置之间的所有行长度,这很痛苦。每次有按键时,你都想存储最后一个光标位置,并注意跳转。

有代码来获取和设置光标位置here

答案 5 :(得分:0)

另外尝试使用服务器端。你可以用任何语言来做。不只是PHP。

if (strlen($textareaContent) <= 72) {
    // Save textareaContent
}
else {
    echo "Your text is longer than 72 characters.";
}

答案 6 :(得分:0)

检查一下:

var t=document.getElementById('textAreaId').value;
if(/^(?:[^\n]{0,73}\n)*$/g.test(t) !== true){
alert('input is invalid');
}

答案 7 :(得分:0)

这是一个旧线程,但是我刚刚开发了一个小jQuery插件解决方案。 签出here。 查找自述文件以获取更多详细信息。我的插件还有更多功能,但基本内容如下:

$(document).ready(function(){
        var linesUsed = $('#linesUsed');
        var charsUsed = $('#charsUsed');
        var errorreading = $('#errors');

        // HANDLES PASTE EVENTS
        $('.line_control').on('paste', function (e) {
            var $el = $(this);
            var lines = $el.attr("lines");
            var chars = $el.attr("chars");
            var errors = [];
            setTimeout(function (e) {
                var newLines = $el.val().split("\n");
                console.log(newLines);
                linesUsed.text(newLines.length);
                charsUsed.text(newLines[newLines.length - 1].length + 1);
                for (var i = 0, len = newLines.length; i < len; i++) {
                    if (newLines[i].length >= chars) {
                        let line = i + 1;
                        let count = newLines[i].length;
                        errors.push({
                            'line': line,
                            'count': count
                        })
                    }
                }
                if (errors.length > 0) {
                    var html = '<p>Errors:</p>';
                    var alertMessage = "Warning!\n\nYour pasted content has exceeded the line limitations. Please review the following:\n\n"
                    for (var i = 0, len = errors.length; i < len; i++) {
                        html = html + '<span>Line: ' + errors[i]['line'] + '</span></br><span>Count: ' + errors[i]['count'] + '</span></br>'
                        alertMessage = alertMessage + 'Line: ' + errors[i]['line'] + ' Over: ' + (errors[i]['count'] - chars) + ' Count: ' + errors[i]['count'] + '\n';
                    }
                    alert(alertMessage);
                    errorreading.html(html);
                }
                console.log(errors);
                if (newLines.length >= lines) {
                    linesUsed.css('color', 'red');
                    return false;
                } else {
                    linesUsed.css('color', '');
                }
                if (newLines[newLines.length - 1].length >= chars) {
                    charsUsed.css('color', 'red');
                    return false;
                } else {
                    charsUsed.css('color', '');
                }

            }, 100);
        });
        //HANDLES AND KEYDOWN EVENTS
        $('.line_control').keydown(function (e) {
            var lines = $(this).attr("lines");
            var chars = $(this).attr("chars");
            newLines = $(this).val().split("\n");
            linesUsed.text(newLines.length);
            charsUsed.text(newLines[newLines.length - 1].length + 1);
            if (newLines.length > lines && e.keyCode !== 8 && e.keyCode !== 46) {
                linesUsed.css('color', 'red');
                return false;
            } else if (e.keyCode !== 13 && e.keyCode !== 8 && e.keyCode !== 46 && newLines[newLines.length - 1].length >= chars) {
                charsUsed.css('color', 'red');
                return false;
            } else {
                linesUsed.css('color', '');
            }
        });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<textarea class="line_control" lines="2" chars="8" style="resize: none;"></textarea>

答案 8 :(得分:0)

只需扩展katze_sonne的现有答案,即可满足需要限制每行字符数的多个文本区域的需求。

HTML:

<textarea data-row-maxlength = "35" data-limit-row-len = "true" rows = "4"></textarea>

这里的想法是,您在data-row-maxlength中设置最大长度,并且JavaScript定位到data-limit-row-len = "true"

处的任何元素

JavaScript:

$("textarea[data-limit-row-len=true]").on("input focus keydown keyup", function (event) {
    var maxlength = $(this).data("row-maxlength");

    var text = $(this).val();
    var lines = text.split(/(\r\n|\n|\r)/gm); 
    for (var i = 0; i < lines.length; i++) {
        if (lines[i].length > maxlength) {
            lines[i] = lines[i].substring(0, maxlength);
        }
    }
    $(this).val(lines.join(''));
});

答案 9 :(得分:0)

试试这个。

    <textarea name="limit" id="limit" cols="30" rows="10"></textarea>
    <script>
      const text = document.querySelector('#limit');
      const CHAR_LIMIT_PER_LINE = 5;
      const LINES_LIMIT = 6;

      text.addEventListener('keyup', (e) => {
        const lines = e.target.value.split('\n');
        for (let i = 0; i < lines.length; i++) {
          if (lines[i].length < CHAR_LIMIT_PER_LINE) continue;
          lines[i] = lines[i].substring(0, CHAR_LIMIT_PER_LINE);
          lines[i + 1] = `${lines[i].substring(CHAR_LIMIT_PER_LINE + 1)}${lines[i + 1] || ''}`;
        }
        text.value = lines.slice(0, LINES_LIMIT).join('\n');
      });
    </script>

答案 10 :(得分:-1)

您可以在表单提交(onsubmit)或textfield的按键或任何

上调用此方法
if (document.yourformname.textareaname.value.length > maxchars) {
 // too many
}

编辑:这是javascript。您当然也想验证服务器端。