bkoodaa
bkoodaa

Reputation: 5322

How to clear textarea form in HTML/JS

How can I clear a form in HTML/JS without loading external libraries?

Here's what I've tried so far and how they fail:

<input type="reset" value="Reset">

This doesn't clear the form, only resets it to its original value.

form.getElementsByTagName('textarea').innerHTML = ''

This only clears the form if it has not been edited. If the form has been edited, it does nothing. Here's a JSfiddle where these 2 have been combined, but if you edit the textarea and click clear, you can see it doesn't work (source of JSfiddle).

Upvotes: 0

Views: 406

Answers (2)

Prasanna Kumar
Prasanna Kumar

Reputation: 1

Try the following way I edited and it clears the textarea https://gist.github.com/anonymous/76b3c08a2d38ddafc15791501173a6b8

Upvotes: -1

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

Use text[i].value instead of text[i].innerHTML:

function resetForm(form) {
    // clearing inputs
    var inputs = form.getElementsByTagName('input');
    for (var i = 0; i<inputs.length; i++) {
        switch (inputs[i].type) {
            case 'hidden':
            case 'text':
                inputs[i].value = '';
                break;
            case 'radio':
            case 'checkbox':
                inputs[i].checked = false;   
        }
    }
    
    // clearing selects
    var selects = form.getElementsByTagName('select');
    for (var i = 0; i<selects.length; i++)
        selects[i].selectedIndex = 0;
    
    // clearing textarea
    var text= form.getElementsByTagName('textarea');
    for (var i = 0; i<text.length; i++)
        text[i].value= '';
    
    return false;
}
<form method='post' action='someaction.php' name='myform'>

<input type='text' name='text1' value="a value">
<input type='text' name='text2'>

<input type='checkbox' name="check1" checked>Check Me
<input type='radio' name="radio1" value="a" >
<input type='radio' name="radio1" value="b" checked>
<input type='radio' name="radio1" value="c">

<textarea rows="2" cols="20" name='textarea1'>
some text    
</textarea>

<select name='select1'>
  <option value="volvo">Volvo</option>
  <option value="saab" selected>Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

<input type='reset' value='Reset' name='reset' onclick="return resetForm(this.form);">
<input type='submit' value='Submit' name='submit'>

</form>

Upvotes: 3

Related Questions