Home > OS >  While user enters a value separated by comma in an input fields. The how to display the out put in l
While user enters a value separated by comma in an input fields. The how to display the out put in l

Time:11-16

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>

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  •  Tags:  
  • html
  • Related