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>
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>
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.
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>