Textarea 每行限制字符 Jquery 或 Javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5236333/
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 16:18:00  来源:igfitidea点击:

Textarea Limit characters per line Jquery or Javascript

javascriptjquerytextareaword-wrap

提问by kumar

Possible Duplicate:
How to limit number of characters per line in text area to a fixed value.

可能的重复:
如何将文本区域中每行的字符数限制为固定值。

hello Friends,

你好朋友,

I have a textarea field in my view.

在我看来,我有一个 textarea 字段。

I need to set per line 72 characters length.

我需要设置每行 72 个字符的长度。

that is user is entering more than 72 chracter per line I need go to next line.

即用户每行输入超过 72 个字符,我需要转到下一行。

How to set these limits using jquery or javascript?

如何使用 jquery 或 javascript 设置这些限制?

Thanks

谢谢

回答by Juan Mendes

This is not standard, but it works in many browsers, test it.

这不是标准的,但它适用于许多浏览器,测试它。

http://www.htmlcodetutorial.com/forms/_TEXTAREA_WRAP.html

http://www.htmlcodetutorial.com/forms/_TEXTAREA_WRAP.html

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

Setting wrap to hard makes it send new lines to the server. Setting it to soft only breaks it visually.

将 wrap 设置为 hard 会使其向服务器发送新行。将其设置为软只会在视觉上破坏它。

回答by Hussein

I may be a bit late posting this answer, but this is best done with javaScript to ensure browser compatibility. With jQuery we can do

我发布这个答案可能有点晚了,但最好使用 javaScript 来确保浏览器兼容性。使用 jQuery 我们可以做到

var count= 1;
var chars= 3;
$('#mytext').keydown(function() {
        var v = $(this).val();
        var vl = v.replace(/(\r\n|\n|\r)/gm,"").length;   
    if (parseInt(vl/count) == chars)
    {
        $(this).val(v + '\n');
        count++;
    }
});

Check working example at http://jsfiddle.net/ZWVad/2/

http://jsfiddle.net/ZWVad/2/检查工作示例

回答by jondavidjohn

No need to use javascript for this. There is a HTML attribute built into the <textarea>tag.

无需为此使用 javascript。<textarea>标签中内置了一个 HTML 属性。

See some documentation here.

请参阅此处的一些文档。

example for your use

示例供您使用

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

Using a HARDWrap actually sets carriage returns when the line is wrapped.

使用HARDWrap 实际上会在换行时设置回车符。

回答by Daniel Rodriguez MSFT

If you put this in your html:

如果你把它放在你的html中:

<TEXTAREA ID="12" WRAP=HARD></TEXTAREA>
<TEXTAREA ID="92" WRAP=HARD></TEXTAREA>

You can do this with jQuery:

你可以用 jQuery 做到这一点:

$("#12").attr({cols: 12});
$("#92").attr({cols: 92});