最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Append a <br> tag to a value inside a textarea jquery - Stack Overflow

programmeradmin3浏览0评论

How would you append a
tag on a value inside a textarea, it only appends it after a keypress of SHIFT+ENTER,

here is my code to append on the text area and it does not work??

$('#textarea').append("<br/>"); i think there are still something lacking.

DEMO

Thank you. . .

How would you append a
tag on a value inside a textarea, it only appends it after a keypress of SHIFT+ENTER,

here is my code to append on the text area and it does not work??

$('#textarea').append("<br/>"); i think there are still something lacking.

DEMO

Thank you. . .

Share Improve this question asked Jun 7, 2012 at 6:11 tomexsanstomexsans 4,5274 gold badges37 silver badges49 bronze badges 1
  • \n is newline; <br> is not. – Derek 朕會功夫 Commented Jun 7, 2012 at 6:20
Add a ment  | 

2 Answers 2

Reset to default 8

Are you actually wanting to place the characters in the value?

​$("textarea").val(function(i,v){
    return v + "<br/>";
});​​​​

Or simply add a new line?

​$("textarea").val(function(i,v){
    return v + "\nfoo";
});​​​​​​​

Fiddle: http://jsfiddle/jonathansampson/SNeyy/

If you want to respond only to shift + enter:

$("textarea").on("keypress", function(e){
    if ( e.which === 13 && e.shiftKey ) {
        $(this).val(function(i,v){
            return v + "<br/>"; // or return v + "\n"; (whatever you want)
        });
    }
});​​​​

Fiddle: http://jsfiddle/jonathansampson/SNeyy/1/

You are trying to change the value of the textarea. To add the string "<br/>" you have to use

$('#textarea').val($('#textarea').val() + '<br/>');

and to add a new line you have to use

$('#textarea').val($('#textarea').val() + "\n");

Textarea can have only a text node as its child. <textarea><br/></textarea> is incorrect usage. If you want to add the string "<br/>", the html code should be

<textarea>&lt;br/&gt;</textarea>

and to add a new line, the html code should be

<textarea>
</textarea>

In other words, you cannot use <textarea><br/></textarea>

发布评论

评论列表(0)

  1. 暂无评论