Html 如何使用javascript使用html中的按钮清除文本区域?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15968911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:28:14  来源:igfitidea点击:

How to clear text area with a button in html using javascript?

javascripthtmlbuttontextareaclear

提问by noobprogrammer

I have button in html

我在 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?

如果我有一个外部 javascript (.js) 函数,我应该写什么?

回答by Alessandro Minoccheri

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

通过在按钮单击上添加功能来更改您的 html

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

Try this in your js file:

在你的 js 文件中试试这个:

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

回答by Rishabh

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

您需要附加一个click事件处理程序并从该处理程序中清除 textarea 的内容。

HTML

HTML

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

JS

JS

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

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

and here's the working demo.

这是工作演示

回答by Ali Shah Ahmed

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

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

你只需要设置 onclick 事件,在这个 onclick 事件上调用你想要的函数。

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

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

以上函数将文本区域的值设置为空字符串。

回答by A.A Noman

Your Html

你的 HTML

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

Your Javascript

你的 JavaScript

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

回答by Ivo

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

您可以简单地将ID属性用于表单并将<textarea>标签附加到表单,如下所示:

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