如何在textarea中动态添加新行;javascript 或 jquery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21288498/
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
How to dynamically add a new line in a textarea; javascript or jquery
提问by Afzaal Ahmad Zeeshan
I am developing a keyboard plugin. Which requires that if the user clicks on the enterkey, then it must add the newline in that textarea.
我正在开发一个键盘插件。这要求如果用户单击该enter键,则必须在该文本区域中添加换行符。
I have tried adding other characters, such as a b c etc. But in case of newline I know a newline in js is added using
我曾尝试添加其他字符,例如 abc 等。但在换行的情况下,我知道 js 中的换行是使用添加的
\n
But, when I try to append this to the textarea it just adds that to the textarea's text. While I want it to start a newline. How can I get the new line?
但是,当我尝试将其附加到 textarea 时,它只会将其添加到 textarea 的文本中。虽然我希望它开始换行。我怎样才能得到新的线路?
Here is the code that runs with each click:
这是每次单击时运行的代码:
$('#vboard li').click(function () {
CurVal = $(LastFocused).val();
$(LastFocused).val(CurVal + $(this).attr('id'));
$(LastFocused).focus();
});
The above code executes and appends the current button's value to the element. When I click on enter key, it gives me output as value + '\n' for example:
上面的代码执行并将当前按钮的值附加到元素。当我点击回车键时,它给我输出值 + '\n' 例如:
If the value was afzaal, then after the click it would change to afzaal\n instead of starting a new line.
如果值是 afzaal,那么在点击之后它会变成 afzaal\n 而不是开始一个新行。
How would I get the newline in textarea?
我如何在 textarea 中获得换行符?
回答by Milindu Sanoj Kumarage
You need to add a new new dynamicaly, right? Give this a try and see if this is what you wanted.
您需要添加一个新的动态,对吗?试试这个,看看这是否是你想要的。
$('textarea').html($('textarea').val()+' Something');
I'm setting html
of textarea instead of its val
我正在设置html
textarea 而不是它的val
It seems even this works fine
似乎即使这样也能正常工作
$('textarea').val($('textarea').val()+'\nSomething');
回答by Amir
this one should work with vanila Javascript:
这个应该与 vanila Javascript 一起使用:
var newMessage="please add me to the new line";
var newMessage="请将我添加到新行";
const textarea = document.getElementById('messages');
const textarea = document.getElementById('messages');
element.value += "\n"+ newMessage;
element.value += "\n"+ newMessage;
回答by Anand Jha
try somthing like
尝试类似的东西
<textarea cols='60' rows='8'>This is my first line. This is my second line </textarea>
using
and
will let you on new line without displaying in textarea
使用
and
会让你在新行上不显示在 textarea 中