0

So my problem is that I have a HTML <textarea> element and a button which should clear the textarea. But for some reason this does not work. What am I doing wrong?

function clear() {
  document.getElementById('output').value = '';
}
<textarea spellcheck="false" rows="8" cols="80" id="output">Lorem Impsum</textarea>
<button onclick="clear()">Clear Output</button>
isherwood
  • 52,576
  • 15
  • 105
  • 143

3 Answers3

3

clear is a reserve word in JavaScript. Please change the name of your function.

function clearText() {
   document.getElementById('output').value = '';
}
<textarea spellcheck="false" rows="8" cols="80" id="output">Lorem Impsum</textarea>
<button onclick="clearText()">Clear Output</button>
Sudhir Ojha
  • 3,219
  • 2
  • 12
  • 24
1

You're clearing the HTML property, but the function name is reserved. To clear the element you can do:

function clearOutput() {
  const el = document.getElementById('output');
  
  el.value = '';
}

As a side note, you really shouldn't use the onclick attribute, it's better to bind events using addEventListener.

jahilldev
  • 3,271
  • 4
  • 31
  • 47
1

Textarea uses .innerHTML not .value and also clear() name wont work because it is already defined in vanilla javascript so clear1(). The below code should work -

function clear1() {
  document.getElementById('output').innerHTML = '';
}
<textarea spellcheck="false" rows="8" cols="80" id="output">Lorem Impsum</textarea>
<button onclick="clear1()">Clear Output</button>
Archit Gargi
  • 583
  • 3
  • 18