44

I have button in html

<input type="button" value="Clear"> 
<textarea id='output' rows=20 cols=90></textarea>

If I have an external javascript (.js) function, what should I write?

1
  • also can do as general $('textarea').val(''). Commented Jun 24, 2014 at 4:28

5 Answers 5

84

Change in your html with adding the function on the button click

 <input type="button" value="Clear" onclick="javascript:eraseText();"> 
    <textarea id='output' rows=20 cols=90></textarea>

Try this in your js file:

function eraseText() {
    document.getElementById("output").value = "";
}
Sign up to request clarification or add additional context in comments.

1 Comment

By far most elegant and simple.
9

You need to attach a click event handler and clear the contents of the textarea from that handler.

HTML

<input type="button" value="Clear" id="clear"> 
<textarea id='output' rows=20 cols=90></textarea>

JS

var input = document.querySelector('#clear');
var textarea = document.querySelector('#output');

input.addEventListener('click', function () {
    textarea.value = '';
}, false);

and here's the working demo.

2 Comments

prior to IE 9 addEventListener does not exist, this should be noted.
indeed, hence use attachEvent('click', function () {}); for IE8 and below. Also instead of querySelector use getElementById for IE7 and below. Cheers!
6

Using the jQuery library, you can do:

<input type="button" value="Clear" onclick="javascript: functionName();" >

You just need to set the onclick event, call your desired function on this onclick event.

function functionName()
{
    $("#output").val("");
}

Above function will set the value of text area to empty string.

1 Comment

if you use a library that is not mention by the question you should tell which one you use. for an onclick the javascript: prefix is not required because it is already clear that it is javascript. anyway if you recommend a library like jquery, you probably also should show how to do add event listeners with that library instead of mixing them into the html code.
1

Your Html

<input type="button" value="Clear" onclick="clearContent()"> 
<textarea id='output' rows=20 cols=90></textarea>

Your Javascript

function clearContent()
{
    document.getElementById("output").value='';
}

Comments

-4

You can simply use the ID attribute to the form and attach the <textarea> tag to the form like this:

<form name="commentform" action="#" method="post" target="_blank" id="1321">
    <textarea name="forcom" cols="40" rows="5" form="1321" maxlength="188">
        Enter your comment here...
    </textarea>
    <input type="submit" value="OK">
    <input type="reset" value="Clear">
</form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.