BradTheBrutalitist BradTheBrutalitist - 6 months ago 31
jQuery Question

jQuery: How Do I Append Text From textarea To paragraph After I Presses Enter?

I want to essentially move the text the user types from the

textarea
into the paragraph of my choice when the user
presses enter
. The problem is enter is already programmed into
textarea
. It's function is to make a new line but I want to replace that function with:

When the user presses enter it moves there text from the textarea to

Here is my html code for the paragraph and textarea:

<hr id="LineOne">
<p id="UserInput"></p>
<hr id="LineOne">
<textarea placeholder="Type Message Here:"></textarea>


And here is my jQuery (Here is where I think the problem is happening so pay more attention here:

$(document).ready(function(){
$('textarea').bind("enterKey",function(e){
textarea.moveTo('#UserInput');
});
});
$('textarea').keyup(function(e){
if(e.keyCode == 13){
$(this).trigger("enterKey");
}
});


I am very noobie/newbie with jQuery and I found the from another problem in Stack overflow and edited it to fit my needs but it isn't working the way I want it to can you tell me why it wont work and how to fix it.

And also, how can I make so after the user makes a message it puts a space after the message they sent so it doesn't append every message they make the the same line?

I want to make it so if I remove the text from textarea, paragraph (or UserInput) will still have that text saved.

Answer

You might looking for this

$(document).ready(function() {
  $('textarea').keyup(function(e) {
    // Regex for matching new lines which will be replaced with <br />
    // to make new line onto the paragraph.
    var newval = $(this).val().replace(/(?:\r\n|\r|\n)/g, '<br />');
    var para = $('#myparagraph');
    
    // Keycode 13 is the Enter key
    if (e.keyCode == 13) {
      // Append the all text inside the textarea into paragraph
      para.append(newval);
      $(this).val(''); // Clear the textbox
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr/><p id="myparagraph"></p><hr/>
<textarea></textarea>