-1

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'>
  • Inline event handlers like `onclick` are [bad practice](/q/11737873/4642212). They’re an [obsolete, cumbersome, and unintuitive](/a/43459991/4642212) way to listen for events. Always [use `addEventListener`](//developer.mozilla.org/en/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. A ` – Sebastian Simon Dec 26 '22 at 03:01

1 Answers1

2

Use eventListeners via addEventListener

        window.addEventListener("load", onLoadHandler);
        function onLoadHandler(){
            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>
tatactic
  • 1,379
  • 1
  • 9
  • 18