<input id="input"> <ul id="ul"> <li>Текст 1</li> <li>Текст 2</li> <li>Текст 3</li> </ul> 

How about having such a structure to fill in input text from li on click?

    2 answers 2

    Html:
    It is not necessary to assign to the elements IDs the same as the names of existing tags. Otherwise, you will very quickly start to get confused in three Christmas trees.

      <input id="myInput"> <ul id="myList"> <li>Текст 1</li> <li>Текст 2</li> <li>Текст 3</li> </ul> 

    Javascript:
    No need to hang handlers on each item in the list. We hang the handler on the list itself, and then we catch the event.target. This is called event delegation , and is used to not produce many identical handlers.

     var myList = document.getElementById('myList'), myInput = document.getElementById('myInput'); myList.addEventListener('click', function(event){ myInput.value = event.target.innerHTML; }); 
    • Cool, did not know about this. - smellyshovel pm
    • That's just my error throwing your code (script.js: 74 Uncaught TypeError: Cannot read property 'addEventListener' of null) - smellyshovel
    • @MatveyMamonov, pay attention, I also changed html - Duck Learns to Take Cover
    • And, yes, I did not notice right away. How does it work? We catch a click on ul, and then how does it work? - smellyshovel
    • Identical I do not argue. Live and learn what is called. - smellyshovel
     let lis = document.querySelectorAll("li"); for (let i = 0; i < lis.length; i++) { lis[i].addEventListener("click", function() { replaceToInput(lis[i]); }); } function replaceToInput(elem) { input = document.getElementById("input"); input.setAttribute("value", elem.innerHTML); } 

    I tested it myself, now the code is working.

    • That you get to create input id = "input" I understand correctly? - user33274
    • I will also try it now - Identin
    • @LenovoID Or change to your id - idon
    • Identon, but can not you turn to the input without an identifier? - user33274 4:47 pm
    • @LenovoID he already has a vehicle. - smellyshovel