开发者

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.


Or if jquery tag was there for a reason:

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


You should use value:

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


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


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.


just give like this

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜