Timofey Trofimov
Timofey Trofimov

Reputation: 1174

Why does assigning to `.innerHTML` of a `<textarea>` node not work? What should I use instead?

I use .innerHTML to add text in textarea. But If I starting edit text in textarea by myself script stops working.

Here it is:

var addPort = function (name) {
    switch(name) {
    case 'name1':
        var code = "text1"; 
        break
    case 'name2':
        var code = "text2";
        break
    case 'name3':
        var code = "text3";
        break
    default:
        break
    }
    document.getElementById("codeArea").innerHTML += code;
};
<textarea id="codeArea" name="codeAreaPost">abcdef</textarea>
<p> <button onclick="addPort()">addPort()</button>

Upvotes: 4

Views: 1699

Answers (3)

dumbass
dumbass

Reputation: 27228

Modifying .innerHTML of a <textarea> element does not, in general, modify its current contents – it only modifies the initial contents, which is what a type="reset" button will reset it to. Only if the control was not modified, will updating the initial state also update the current state.

To modify the current contents of the control, use the .value property.

document.querySelector('textarea').value +=
  " then press the other";

document.querySelector('button[type="button"]')
  .addEventListener('click', ev => {
    document.querySelector('textarea').innerHTML =
      "don't type anything here…";
  });
<form>

<textarea rows="5" cols="40">
type something here and press one of the buttons…</textarea>

<p>
<button type="reset">Reset</button>
<button type="button">Change innerHTML</button>

Upvotes: 0

Pranay Rana
Pranay Rana

Reputation: 176946

its just replace innerHTML by value property

document.getElementById("codeArea").value

not innerHTML

Upvotes: 7

Mathias Schwarz
Mathias Schwarz

Reputation: 7197

innerHTML will parse the value as HTML and make the resulting DOM a child of your text area. This is not what you want. Try the value attribute instead:

document.getElementById("codeArea").value += code;

Upvotes: 1

Related Questions