1

I have the following JavaScript code:

var c=document.createElement("textarea");
c.value="what ever";
document.body.appendChild(c);

This supposed to add a textarea tag at the end of my page. The textarea is added, but it doesn't have the value set.

How can I solve that?

Enter image description here

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Thomas Carlton
  • 5,344
  • 10
  • 63
  • 126
  • works fine here https://jsfiddle.net/qpxy53ue/ as well as in the snippet in this page – charlietfl Oct 26 '20 at 04:44
  • because it is a property, it is not going to update the view source. – epascarello Oct 26 '20 at 04:50
  • Don't know the reason, why it doesn't show the value attribute but It does update the value of Element. Event `Input` doesn't show the `value` in DOM if you add value from JS. But If you add element using HTML, It does show the attributes. `` - It does shows – Naren Oct 26 '20 at 04:54
  • May be @epascarello right, Does it mentioned anywhere? – Naren Oct 26 '20 at 04:55
  • Unclear why someone would need to see the value in the view source unless they are trying to clone elements with innerHTML.... – epascarello Oct 26 '20 at 04:56

1 Answers1

2

Use innerHTML to set the value of textarea.

var c=document.createElement("textarea");
c.innerHTML="what ever";
document.body.appendChild(c);
Derek Wang
  • 10,098
  • 4
  • 18
  • 39
  • 1
    Works fine with `value` which is preferred once in DOM – charlietfl Oct 26 '20 at 04:45
  • Although this is the correct answer (and works for most input-type tags), if you want to display a hint for the user, you should rather use the placeholder attribute. – ego2509 Oct 26 '20 at 04:53
  • you should consider to [read this](https://stackoverflow.com/questions/5314186/javascript-get-textarea-input-via-value-or-innerhtml) if you're going to use `innerHTML`. I don't think using `innerHTML` is not the right way to update the value – Naren Oct 26 '20 at 04:59