jQuery FAQ: How do you create a textarea using jQuery? Also, how do I insert content (text or HTML) into a textarea with jQuery?
I don't know if this will make any sense without showing my HTML, but I just used the following jQuery code to (a) get contents from a specific div tag, (b) add a textarea just before that div, (c) put the HTML contents into the new textarea, then (d) remove the original div. So, in essence, I created a new textarea with jQuery and inserted HTML into that textarea, but I got the HTML from my original div.
Given that introduction, here's my jQuery code to create a textarea, and then insert text into that textarea:
<script type="text/JavaScript"> // created by alvin alexander // http://www.devdaily.com jQuery(document).ready(function(){ // divs will be working with var divToDelete = 'div.field-field-se-results'; var divToAppendTo = 'div.field-field-recommended-url'; // get the html from the divToDelete var htmlStr = jQuery(divToDelete).html(); // put the new textarea before the other div jQuery(divToAppendTo).append('<textarea rows="5" cols="50">'); jQuery(divToAppendTo).append('</textarea>'); // insert the original html into my new textarea jQuery('textarea').val(htmlStr); // remove the div i got the html from originally jQuery(divToDelete).remove(); }); </script>
I won't claim this code is great by any means, but it got the job done. I imagine I can probably create one or two objects in there, but this worked, and I need to move on to something else.
jQuery textarea - Notes
The two strings that begin with "div." represent div classes in my HTML I wanted to match. I used this code on a Drupal website (prototype) that I'm creating.
One potential flaw in this code is that if your HTML page has more than one textarea, this code will insert that HTML into every textarea, but since I only have the textarea I created, this works fine.
I could have used the text() function initially instead of the html() function, but I believe that function strips the HTML from what it grabs, whereas I wanted to keep the original HTML code for my purposes.
jQuery textarea - Summary
If you want to create a textarea using jQuery, and then populate that textarea with some content, I hope this jQuery example is helpful. If you have suggestions for cleaning up the code, just leave a comment below.