zdcobran
zdcobran

Reputation: 311

Write inside text area with Javascript

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.

Upvotes: 4

Views: 27244

Answers (6)

Ari
Ari

Reputation: 4969

If you want to write long text in the textarea, you can use this way:

HTML

<textarea id="theId"></textarea>

jQuery

var a = 'Test textarea content. <a href="http://google.com">Google</a>" ';

$("#theId").val(a);

JS FIDDLE

Upvotes: 0

Jonathon Bolster
Jonathon Bolster

Reputation: 15961

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.

Upvotes: 2

rahul
rahul

Reputation: 187030

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

Upvotes: 3

Anish Joseph
Anish Joseph

Reputation: 1026

just give like this

$("#ID").val("<img src='images/logo.png' />");

Upvotes: 0

naugtur
naugtur

Reputation: 16915

Or if jquery tag was there for a reason:

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

Upvotes: 5

Sarfraz
Sarfraz

Reputation: 382696

You should use value:

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

Upvotes: 4

Related Questions