Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

While user enters a value separated by comma in an input fields. The how to display the out put in list format

Here in this input fields. While user enters a value which is separated by a comma. For example like "apple,Banana,grapes,mango". So here if user enters the value in this format. Then I want to display the output in list format like

apple
Banana
grapes
mango

So if it can be done please let know how to do this. Below is my code where I have tried

<input type='text' id='idea' />
<input type='button' value='add to list' id='add' />
<ul id='list'></ul>
<script>
document.getElementById("add").onclick = function() {
    //First things first, we need our text:
    var text = document.getElementById("idea").value; //.value gets input values

    //Now construct a quick list element
    var li = "<li>" + text + "</li>";

    //Now use appendChild and add it to the list!
    document.getElementById("list").appendChild(li);
}
</script>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You were almost there, but you can not append HTML in strings, you need to create proper list item objects and append those:

document.getElementById("add").onclick = function() {
  // cache the list
  const list = document.getElementById("list");
  
  //First things first, we need our text:
  const items = document.getElementById("idea").value.split(','); //.value gets input values, .split(',') makes it an array of values
  
  // foreach entry in the text array, create and append an li
  for (const item of items) {
    const li = document.createElement('li');
    li.textContent = item;
    list.appendChild(li);
  }
}
<input type='text' id='idea' />
<input type='button' value='add to list' id='add' />
<ul id='list'></ul>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading