简体   繁体   中英

How to display text in a textarea by clicking a link

Can I have a link that when clicked displays text inside a textarea?

This is what I have.

<script type="text/javascript">
mybutton: onclick {
document.myform2.mytextfield2.value = "Test";
}
</script>

<form name="myform2">
<input type="button" name="mybutton" value="Go">
<input type="text" name="mytextfield2">
</form>

Please tell me what I got wrong.

The problem is that mybutton: onclick {... } is not an executable statement; it's a fragment of code.

There are several ways to fix your code.

1. Declare a function in the script, and declare an onclick event handler in the button.

<script type="text/javascript">
function myfunc() {
document.myform2.mytextfield2.value = "Test";
}
</script>

<form name="myform2">
<input type="button" name="mybutton" value="Go" onclick="myfunc()">
<input type="text" name="mytextfield2">
</form>

OR 2. Give the button an ID, put the script block after the button, and modify the event handler registration code.

<form name="myform2">
<input type="button" name="mybutton" value="Go" id="mybutton">
<input type="text" name="mytextfield2">
</form>

<script type="text/javascript">
document.getElementById("mybutton").onclick = function() {
document.myform2.mytextfield2.value = "Test";
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM