Change paragraph text dynamically with jQuery?

Carson picture Carson · Aug 9, 2010 · Viewed 80.8k times · Source

I want to take the information typed into a text field and display it in a paragraph elsewhere on the page. Basically, exactly what is happening below as I'm type this (go to post a question and start typing in the main text box and you'll see what I mean).

Any idea how to do this? The page has so much JavaScript on it I can't find how they did it.

Answer

Sarfraz picture Sarfraz · Aug 9, 2010

I think you are looking for this.

Here is how your html should look like:

<textarea id="txt" style="width:600px; height:200px;"></textarea>
<p id="preview"></p>

And jQuery:

$(function(){
  $('#txt').keyup(function(){
     $('#preview').text($(this).val());
  });
});

This grabs the value of textarea on its keyup event and later the paragraph's text is changed (text() method) with that of textarea $(this).val().