0

I have a simple textarea with a button:

I change the content of the textarea with

$("button.test").click(function(){
   $("#config_oh").contentEditable = true;
$("#config_oh").html("Hello World);

});

This works. But if I type inside the textarea and re-run the script, it doesn't work: The content is there (I can see it with Chrome inspector) but no content is displayed on the webpage. Why?

If I update the the content of the textarea with val(), it works, but no HTML rendering is performed, e.g. I see html special chars.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
gdm
  • 7,647
  • 3
  • 41
  • 71

3 Answers3

0

replace

$("#config_oh").html("Hello World);

with

$("#config_oh").val("Hello World");

Captain Squirrel
  • 237
  • 5
  • 15
  • I know, but 1) why this behaviour; 2) the val is not rendered....html special chars are being shown – gdm Nov 07 '16 at 11:56
  • Any value you put into the textarea, through manually typing or using a preset value (Like we are in the example), is going to be rendered in plaintext. – Captain Squirrel Nov 07 '16 at 11:59
  • If you wanted to render html on the page, your best bet would be to add the contentEditable tag onto a div element. Something similar to [this](http://jsbin.com/oBiBoBE/10/edit?html,output) would do it. – Captain Squirrel Nov 07 '16 at 12:02
  • It is not true: If I do .html(" ";") this is rendered as html (the first time only) – gdm Nov 07 '16 at 12:03
  • That behavior is quite strange. – Captain Squirrel Nov 07 '16 at 12:09
  • Unfortunately, your not going to be able to render actual div's or any actual html tags similar to that without using something similar to what i linked before. Special html characters however, i'm unsure as to why it would render out first time round and refuse to do it thereafter – Captain Squirrel Nov 07 '16 at 12:11
0

Personally, I suggest to make a custome div with conteneditable=true, as suggested in the comments. In this way, .html() method works as usual.

<style>
        .editable {
            width: 100%;
            height: 200px;
            border: 1px solid #ccc;
            padding: 5px;
            resize: both;
            overflow: auto;
        }

        </style>
<button class="test">Click</button>
<div class="editable" contenteditable="true" id="config_oh"> MY TEXT HERE </div>

<script>
$("button.test").click(function(){   
   $("#config_oh").html("Hello World);
});
</script>

In this way, even after typing inside the "textarea" the button click works as expected.

gdm
  • 7,647
  • 3
  • 41
  • 71
0

you have to set the text in the input type box. you use val(). input type have a property value. eg:

$("#config_oh").val("Hello World");

this should be worked

Liam
  • 27,717
  • 28
  • 128
  • 190