Clear textarea JavaScript

How to clear textarea on button click using JavaScript

Posted by Ervin Adams on August 3, 2022

Clear textarea JavaScript

How to clear textarea on button click using JavaScript

Posted by Ervin Adams on August 3, 2022

Here is how you clear a textarea on button click in JavaScript.

Step 1. Add onClick attribute with moreInfo() function to button

Step 2. Get the specified textarea element using document.getElementById()

Step 3. Clear the textarea by using the attrubute value

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wecode101 clear textarea</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
  <main>
    <!--Main layout-->
    <div class="container">
        <div class="col-9 mx-auto">
            <div class="mb-3">
                <textarea id="more-info" class="form-control" name="more-info"></textarea>
            </div>
            <button type="button" class="btn btn-primary" onClick='clearInfo()'>clear info</button>
        </div>     
    </div>
  </main>
</body>
</html>

JS

function clearInfo(){

    const moreInfo = document.getElementById('more-info'); //get the textarea

    moreInfo.value = ''; //clear the textarea
}