Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering HTML inside textarea

I need to be able to render some HTML tags inside a textarea (namely <strong>, <i>, <u>, <a>) but textareas only interpret their content as text. Is there an easy way of doing it without relying on external libraries/plugins (I'm using jQuery)? If not, do you know of any jQuery plugin I could use to do this?

like image 408
The Coding Monk Avatar asked Oct 18 '22 04:10

The Coding Monk


People also ask

Can you render HTML inside textarea?

An HTML text area can't render HTML. However, we can make a div's content editable with the contenteditable attribute. Therefore. we can use an editable div as we do with a text area but with HTML content.

Can I put Div inside textarea?

You cannot place HTML elements inside a text area, only text content. only text content covers that part.

Can we use value attribute in textarea?

From the MDN documentation: " <textarea> does not support the value attribute".


2 Answers

This is not possible to do with a textarea. You are looking for a content editable div, which is very easily done:

<div contenteditable="true"></div>

jsFiddle

div.editable {
    width: 300px;
    height: 200px;
    border: 1px solid #ccc;
    padding: 5px;
}

strong {
  font-weight: bold;
}
<div contenteditable="true">This is the first line.<br>
See, how the text fits here, also if<br>there is a <strong>linebreak</strong> at the end?
<br>It works nicely.
<br>
<br><span style="color: lightgreen">Great</span>.
</div>
like image 283
mekwall Avatar answered Oct 19 '22 16:10

mekwall


With an editable div you can use the method document.execCommand (more details) to easily provide the support for the tags you specified and for some other functionality...

#text {
    width: 500px;
    min-height: 100px;
    border: 2px solid;
}
<div id="text" contenteditable="true"></div>
<button onclick="document.execCommand('bold');">toggle bold</button>
<button onclick="document.execCommand('italic');">toggle italic</button>
<button onclick="document.execCommand('underline');">toggle underline</button>
like image 37
Sampath Liyanage Avatar answered Oct 19 '22 16:10

Sampath Liyanage