Javascript 使用jQuery限制textarea中的行数并显示行数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6501043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:03:53  来源:igfitidea点击:

Limit number of lines in textarea and Display line count using jQuery

javascriptjqueryhtmlvalidationtextarea

提问by chainwork

Using jQuery I would like to:

使用 jQuery 我想:

  • Limit the number of lines a user can enter in a textarea to a set number
  • Have a line counter appear that updates number of lines as lines are entered
  • Return key or /n would count as line
  • 将用户可以在 textarea 中输入的行数限制为设定的数量
  • 出现一个行计数器,在输入行时更新行数
  • 返回键或 /n 将算作行

Kudos to anyone who can help!

感谢任何可以提供帮助的人!

$(document).ready(function(){
  $('#countMe').keydown(function(event) {
    // If number of lines is > X (specified by me) return false
    // Count number of lines/update as user enters them turn red if over limit.

  });   
});


<form class="lineCount">
  <textarea id="countMe" cols="30" rows="5"></textarea><br>
  <input type="submit" value="Test Me">
</form>

<div class="theCount">Lines used = X (updates as lines entered)<div>

For this example lets say limit the number of lines allowed to 10.

对于此示例,假设将允许的行数限制为 10。

Thanks all!

谢谢大家!

回答by Samuel Liew

html:

html:

<textarea id="countMe" cols="30" rows="5"></textarea>
<div class="theCount">Lines used: <span id="linesUsed">0</span><div>

js:

js:

$(document).ready(function(){

    var lines = 10;
    var linesUsed = $('#linesUsed');

    $('#countMe').keydown(function(e) {

        newLines = $(this).val().split("\n").length;
        linesUsed.text(newLines);

        if(e.keyCode == 13 && newLines >= lines) {
            linesUsed.css('color', 'red');
            return false;
        }
        else {
            linesUsed.css('color', '');
        }
    });
});

fiddle: http://jsfiddle.net/XNCkH/17/

小提琴:http: //jsfiddle.net/XNCkH/17/

回答by Antonio Novak

Here is little improved code. In previous example you could paste text with more lines that you want.

这里有一些改进的代码。在前面的示例中,您可以粘贴带有更多行的文本。

HTML

HTML

<textarea data-max="10"></textarea>
<div class="theCount">Lines used: <span id="linesUsed">0</span></div>

JS

JS

jQuery('document').on('keyup change', 'textarea', function(e){

        var maxLines = jQuery(this).attr('data-max');        
        newLines = $(this).val().split("\n").length;

        console.log($(this).val().split("\n"));

        if(newLines >= maxLines) {
            lines = $(this).val().split("\n").slice(0, maxLines);
            var newValue = lines.join("\n");
            $(this).val(newValue);
            $("#linesUsed").html(newLines);
            return false;
        }

    });

回答by mattdlockyer

For the Reactfans out there, and possibly inspiration for a vanilla JS event handler:

对于那里的React粉丝,以及可能的原版 JS 事件处理程序的灵感:

onChange={({ target: { value } }) => {
    const returnChar = /\n/gi
    const a = value.match(returnChar)
    const b = title.match(returnChar)
    if (value.length > 80 || (a && b && a.length > 1 && b.length === 1)) return
    dispatch(setState('title', value))
}}

This example limits a textarea to 2 lines or 80 characters total.

本示例将一个 textarea 限制为 2 行或总共 80 个字符。

It prevents updating the state with a new value, preventing React from adding that value to the textarea.

它阻止使用新值更新状态,阻止 React 将该值添加到 textarea。

回答by Alexandr Sargsyan

A much ugly , but somehow working example specify rows of textarea

一个非常丑陋但以某种方式工作的示例指定文本区域的行

<textarea rows="3"></textarea>

and then in js

然后在js中

   $("textarea").on('keydown keypress keyup',function(e){
       if(e.keyCode == 8 || e.keyCode == 46){
           return true;
       }
       var maxRowCount = $(this).attr("rows") || 2;
        var lineCount = $(this).val().split('\n').length;
        if(e.keyCode == 13){
            if(lineCount == maxRowCount){
                return false;
            }
        }
        var jsElement = $(this)[0];
        if(jsElement.clientHeight < jsElement.scrollHeight){
            var text = $(this).val();
            text= text.slice(0, -1);
            $(this).val(text);
            return false;
        }

    });