Home > Back-end >  How to display a Text in an input field on a button click?
How to display a Text in an input field on a button click?

Time:12-26

i want any text like hello world to be appeared in a input field when i click the button. How can i do that?

enter code here

<button class='submit' onclick="myFunction()"> Click Me </button>
<input type= 'text' id='demo'>

CodePudding user response:

Use eventListeners via addEventListener

        window.addEventListener("load", onl oadHandler);
        function onl oadHandler(){
            let button = document.getElementById("myButton");
            button.addEventListener("click",buttonClick);
        }
        function buttonClick(e){
            let input = document.getElementById("textInput");
            input.value = "Hello world!";
        }
    <div>
        <input id="textInput">
    </div>
    <div>
        <button id="myButton">
            write in input
        </button>
    </div>

  • Related