views:

387

answers:

4

Hey there... here's an easy one (that I'm struggling with)! I have a textarea, a button, and an empty div. All I want to do is insert the updated contents of the textarea into the div onClick of the button. Here's what I've got so far:

<html>
 <head>
  <script type="text/javascript" src="jquery.js"></script>
  <script type="text/javascript">
   function get_text() {
    $("#preview").replaceWith( $("#editor").val() );
   }
  </script>
 </head>
 <body>
  <form>
   <textarea name="editor" id="editor">GrumbleCakes</textarea>
   <input type="button" value="Preview" onclick="get_text();" />
  </form>
  <div id="preview"></div>
 </body>
</html>

It works the first time you click the button... with the value that was in the textarea on page load ("GrumbleCakes"), but that's it. It won't work with any updated text.

Help! Thanks in advance!

+1  A: 

You can set the innerHTML or text content of the preview div by using the html or text functions:

$("#preview").html($("#editor").val());
CMS
indeed. replaceWith replaces the <div> and </div> itself. So there's nothing else to replace after first click.
Eimantas
Perfect! Thanks!
Sam
+2  A: 

.replaceWith actually replaces the DOM element. So the div is removed and replaced with the text. Subsequent calls to the function will no longer find the div, since it's been removed.

I think you want to use

.html($("#editor").val()).

womp
A: 

Both

$('#preview").html($("#editor").val())

and

$("#preview").text( $("#editor").val())

should work.

However, .html will allow anyone to inject html or javascript into your site leaving it wide open for cross-site scripting attacks...

Hector Scout
A: 

jikes!!

man you are replacing div with the contents of the textarea. use this function instead:

function get_text(){
    var t=$("editor").val();
    $("#preview").text(t);
}
TheVillageIdiot