Write inside text area with Javascript

25,498

Solution 1

If you want to render some images and anchor tags on the screen then don't use a textarea. Use any other container like <div>, <span>, <p> etc.

$("#yourelementid").html(yourtext);

will put the text (in your case HTML) inside the element with id yourelementid

HTML

<p id="para1"></p>

jQuery

var txt = "<a href='http://www.google.com'>Google</a>";
$("#para1").html(txt);

See a working sample

Solution 2

Or if jquery tag was there for a reason:

$('#writeArea').val(txt);

Solution 3

You should use value:

document.getElementById("writeArea").value = txt;

Solution 4

You can easily do it in jQuery if you just want to set the text of a textarea:

$("#yourid").val("hello");

See it working: http://jsfiddle.net/quQqH/

If you're looking to have HTML in it then it needs to be a container element (such as a div).

// Html
<div id="yourid"></div>

//JavaScript
$("#yourid").html('<a href="#">My link</a>');

Otherwise, another option is to have a Rich Text Editor (like Yahoo Editor) so that it renders the HTML that's in the textarea input - this will make it user editable. This is slightly more complicated, as you'll need to include the correct files to make the editor work. Then just do something like the following:

var myEditor = new YAHOO.widget.SimpleEditor('yourid', {
    height: '200px',
    width: '350px',
    toolbar: 0 // Hides the toolbar
});
myEditor.render();


$("#yourid").val("Click for <a href='http://yahoo.com'>Yahoo</a>");

You can see this working: http://jsfiddle.net/quQqH/1/. In this case, I've removed the toolbar by setting it to 0 but it is customisable to show different buttons, etc. Just remove that line to display the default toolbar.

Share:
25,498
zdcobran
Author by

zdcobran

.... started to learn web, so that I can maintain my own homepage. Beside, I will be learning some programming. Java at the moment.

Updated on September 29, 2020

Comments

  • zdcobran
    zdcobran over 3 years

    I am trying to write something in text area when I click on a link.

    function writeText(txt){
        document.getElementById("writeArea").innerHTML = txt;
    }
    

    I would like to pass html tag in place of txt as parameter to this function so that I can get image, link etc inside text area. Is it possible in Javascript? || JQuery will be good? Pre-thanks.