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
  • 58,414
  • 16
  • 114
  • 157
corv1njano
  • 21
  • 2

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,247
  • 3
  • 14
  • 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,520
  • 4
  • 35
  • 52
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
  • 634
  • 1
  • 8
  • 24