I have a single input
as in follows:
<input type='text' class='txtwarna' name='txtwarna' value=''/>
And, this is HTML with many similar elements, say, cls
, as:
<div class="ct-a">
<ul class='wr'>
<li class='cls color1'>Kuning</li>
<li class='cls color2'>Putih</li>
<li class='cls color3'>Hijau</li>
<li class='cls color4'>Biru</li>
</ul>
</div>
<div class="ct-b">
<ul class='wr'>
<li class='cls color1'>Biru</li>
<li class='cls color2'>Hitam</li>
<li class='cls color3'>Putih</li>
<li class='cls color4'>Merah</li>
<li class='cls color5'>Coklat</li>
<li class='cls color6'>Abu-abu</li>
</ul>
</div>
What I tried – not working:
var strHtml = document.getElementsByClassName("cls");
var valInput = document.getElementsByClassName("txtwarna");
for (var i = 0; i < strHtml.length; i++) {
strHtml[i].addEventListener('click', function() {
valInput.value = strHtml.innerHTML;
});
}
Question: How to get each of the innerHTML string, say, biru, putih, kuning, etc when user clicks on it and insert the innerHTML string into single input value?
The value will be changed based on user’s click.
3
Answers
You can certainly do what you are asking by simply adding a
click
listener to the document and setting theinput.value
to match the clicked element’stextContent
. Here usingElement.matches()
to delegate clicks to theli
elements with a ‘cls’ class.However, it seems like you are actually wanting the functionality of a
select
element.You should set
value
of thevalInput
to overwrite the value.The clicked element is available through
e.target.innerHTML