Home > Blockchain >  How can I add the value of a list item to a textarea?
How can I add the value of a list item to a textarea?

Time:08-31

I want to add the list item chosen to the textarea and if there's something written on the textarea the chosen list item will be added after it.

$('#box li').click(function() {
  $('#id-of-your-textarea').append($(this).text());
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<ul id="box">
  <li>Text1</li>
  <li>Text2</li>
  <li>Text3</li>
</ul>
<textarea id="id-of-your-textarea"></textarea>

CodePudding user response:

So I edited your snippet and honestly, jQuery is too much. If you are learning, I would strongly advise you to learn pure Javascript. It is literally the code that runs under hood of jQuery library.

Below is the snippet that runs like you want with only Javascript, no jQuery, no library, just pure JS.

//Variables Needed for HTML Elements.

const textArea = document.getElementById('id-of-your-textarea'); 
const boxLi= document.getElementById('box').children;

for(let i = 0; i < boxLi.length; i  ){ // Looping To All Children of Box.
  boxLi[i].addEventListener('click', () => {
    textArea.value  = boxLi[i].textContent   '\n' // Hey JS, do that when I click on that very Li element which is adding text Content of Li Element in the Text Area Value.
  })
}
<ul id="box">
  <li>Text1</li>
  <li>Text2</li>
  <li>Text3</li>
</ul>
<textarea id="id-of-your-textarea"></textarea>

  • Related