skip to Main Content

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>

2

Answers


  1. 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>
    Login or Signup to reply.
  2. A pure/vanilla javascript solution could be for example:

    function appendValue(event)
    {
      const tgtTextArea = document.getElementById('textarea'); 
      let srcEl = event.target;
      if (srcEl.tagName == "LI")
      {
        tgtTextArea.value += srcEl.textContent + 'n';
      }
    }
    
    const options= document.getElementById('options');
    options.addEventListener('click', appendValue);
    <ul id="options">
      <li>Text1</li>
      <li>Text2</li>
      <li>Text3</li>
    </ul>
    <textarea id="textarea"></textarea>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search