简体   繁体   中英

Javascript, copy a text in a field by clicking a button

I try to make a simple javascript fonction which will allow me to click on a button, then a text is duplicated into a field.

For example: On my HTML page (or PHP), I have a blank field, a text and a button, like:

THE FIELD
Hello everybody THE BUTTON

When I click on the button, the text "Hello everybody" appears in the field.

Thank you very much if you have a simple code example.

Sim100

You want to use .value . Here you go:

<input type="text" name="foo" id="foo">
<input type="button" onclick="document.getElementById('foo').value = 'Hello everybody'">

What I get from the question is that you want to place the text that comes before the button into the text field. To improve earlier answers, this can be done with the .innerText function.

<html>
    <head>
        <script type="text/javascript">
            function moveTextIntoInput(){
                var text = document.getElementById('text').innerText;
                document.getElementById('text-input').value = text;
            }
        </script>
    </head>
    <body>
        <input type="text" id="text-input"><br/>
        <span id="text">Hi everyone!</span><button onclick="moveTextIntoInput()">Click Me</button>
    </body>
</html>
<input type="text" id="mytextinput">
<br>Hey Guys <button onclick="document.getElementById('mytextinput').value='Hey Guys, thanks for clicking the button';">Click Me</button>

Try it: http://jsfiddle.net/sUYEk/

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