开发者

jquery add newline or linebreak on enter

I have开发者_如何学运维 a simple textarea. Is it possible with jquery to add a 'br' when I hit the enter button? I've read around here, and the only solution I see is to add a linebreak at the very end of the val().

But I need it to work on every enter press.


You can simply split on the line feed:

var content = $('#myTextBox').val();
var contentArray = content.split(/\n/);

and then spit each one out as a paragraph:

$.each(contentArray, function(){
   $('#previewArea').append('<p>' + this + '</p>');
});

If you're just wanting to put the result into a database as you've stated, you can do the same but build it into a string for insersion:

var myOutputVar;
$.each(contentArray, function(){
   myOutputVar += this + '<br />';
});

Based on your comments it looks like you just need the br added when you insert the data into your database. I'm assuming that you're doing this with an ajax post since you've tagged this as a jQuery question.

Either way, you can just send your data to the server and split it up there using your server side language of choice.


meh, it's ok if it doesn't show it. I just need each new line to have a br added for when it gets added to the database

if you're using php you can use nl2br to change the newlines to BRs

alternately you could add extra BRs on enter directly in the textarea: http://jsfiddle.net/F9XZN/


try this

$('#textareaid').bind('keypress', function(e) {
        if(e.keyCode==13){
                // Enter pressed... do anything here...
                   $(this).val(  $(this).val() + "<br/>");


        }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜