简体   繁体   中英

Change HTML textarea with JavaScript

I have the following code in the HTML:

<button onclick="showDescription();">Find book</button>

While in the JavaScript file attached:

function showDescription(){
    document.getElementById("description").value="book";
}

However, whenever I click the button, it only shows the string "book" for 1 second, and disappears. Any idea what went wrong?

Your button is (presumably) inside a <form> .

The default type for a button is submit .

  1. The JavaScript runs
  2. The value is updated
  3. The form is submitted
  4. The page is reloaded
  5. The initial value is displayed again

Don't use a submit button:

<button type="button" onclick="showDescription();">Find book</button>

Alternatively, return false from your event handler:

onclick="showDescription(); return false;"

I'm guessing that button is inside a form, change it from :

<button onclick="showDescription();">Find book</button>

to:

<input type="button" onclick="showDescription();" value="Find book" />

A button has a default type of submit, so it will submit the form and reload the page if it's inside a form element.

Try this code:

<!DOCTYPE html>
<html>
    <head>
        <script>
            function showDescription()
            {
                document.getElementById("description").innerHTML="book";
            }
        </script>
    </head>
    <body>

        <button onclick="showDescription();">Find book</button>

        <textarea id="description" rows="4" cols="50">
        </textarea>

    </body>

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