<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?
<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?
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; }); 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.
Source: https://ru.stackoverflow.com/questions/530423/
All Articles