Home > Mobile >  How can I insert elements in an array to a HTML document using Javascript?
How can I insert elements in an array to a HTML document using Javascript?

Time:12-24

I am trying to add the elements of a list called "taskList" made up of values I get from the input elements.

Can anyone please help me, I don't understand why the elements from the list are not showing.

var taskList = [];

var input = document.getElementById('takeInput');
var button = document.getElementById('addInput');

button.onclick = function(){
    var nHTML = '';
    var userEnteredText = input.value;
        taskList.push(userEnteredText);
    taskList.forEach(function(task){
        nHTML  = '<li>' task '</li>';
    });
    document.getElementsByClassName('taskLists').innerHTML = '<ul>'   nHTML   '</ul>';
}
<div >
    <header>To-Do List</header>
    <div >
            <input id="takeInput" type="text" placeholder="Add your new To-Do">
            <button id="addInput"  type="button" >➕</button>
    </div>
        <div >

        </div>
    <div >
        <span> You have <span ></span> tasks left </span> 
        <button type="button" >Clear All</button>
    </div>
</div>

I tried checking several times but nothing is updating in the HTML document

CodePudding user response:

You shouldn't append to innerHTML, instead, use createElement to make the li, then set innerHTML of that new element to input.value and use appendChild to append it to the list

var input = document.getElementById('takeInput');
var button = document.getElementById('addInput');
var tlist = document.getElementsByClassName('taskLists')[0];

button.onclick = function(){
    let e = document.createElement('li');
    e.innerHTML = input.value
    tlist.appendChild(e)
    
    // Optionally, clear the input field to prevent double adding the same task
    input.value = '';
}
<div >
    <header>To-Do List</header>
    <div >
            <input id="takeInput" type="text" placeholder="Add your new To-Do">
            <button id="addInput"  type="button" >➕</button>
    </div>
        <div >

        </div>
    <div >
        <span> You have <span ></span> tasks left </span> 
        <button type="button" >Clear All</button>
    </div>
</div>

CodePudding user response:

The main mistake was using .getElementsByClassName like it was one element only and not a list (don't ignore the s in elements!).

Anyway I slightly refactored your code to have better strategies for each of its goals and implemented also the logic for clearing the tasks list.

var taskList = [];

var input = document.getElementById('takeInput');
var buttonAdd = document.getElementById('addInput');
var buttonClear = document.getElementById('clearInput');
var tasksList = document.getElementById('tasksList');

buttonAdd.addEventListener('click', (event)=>{  
  addTask(input.value);  
});

buttonClear.addEventListener('click', (event)=>{  
  tasksList = [];
  document.querySelector('#tasksList ul').remove();
});

function addTask(value){
  if(taskList.length == 0){
    document.getElementById('tasksList').append( document.createElement('ul') );
  }
  taskList.push(value);
  const newLI = document.createElement('li');
  newLI.innerText = value;
  document.querySelector('#tasksList ul').append(newLI);
}
<body>
  <div >
  
    <header>To-Do List</header>
    
    <div >
      <input id="takeInput" type="text" placeholder="Add your new To-Do">
      <button id="addInput"  type="button">➕</button>
    </div>
    
    <div id="tasksList">
    </div>
    
    <div >
      <span> You have <span ></span> tasks left </span>
      <button id="clearInput" type="button" >Clear All</button>
    </div>
    
  </div>
</body>

CodePudding user response:

you just needed to use an ID on the tasklist.

getElementsByClassName needs an index, making your question a dupe of What do querySelectorAll and getElementsBy* methods return?:

document.getElementsByClassName('taskLists')[0].innerHTML

That said, here is a full version using recommended eventListener and IDs where relevant.

let tasks = [];
const taskList = document.getElementById('taskLists') 
const input = document.getElementById('takeInput');
const add = document.getElementById('addInput');
const pendingTasks = document.getElementById('pendingTasks');
const clear = document.getElementById('clear');

const showTasks = () => {
  taskList.innerHTML = `<ul>${tasks.map(task => `<li>${task}</li>`).join('')}</ul>`;
  pendingTasks.textContent = `${tasks.length} task${tasks.length != 1 ? "s" : ""}`;
};  
add.addEventListener('click', ()  => {
  var userEnteredText = input.value; 
  tasks.push(userEnteredText);
  showTasks();
});

clear.addEventListener('click', ()  => {
  tasks = [];
  showTasks();
});

taskList.addEventListener('click', (e) => {
  const tgt = e.target.closest('li');
  if (!tgt) return; // not a task
  const task = tgt.textContent;
  tgt.remove()
  tasks = tasks.filter(currentTask => currentTask != task); // remove from list
  showTasks()
});
showTasks(); //init
<div >
  <header>To-Do List</header>
  <div >
    <input id="takeInput" type="text" placeholder="Add your new To-Do">
    <button id="addInput"  type="button">➕</button>
  </div>
  <div id="taskLists"></div>
  <div >
    <span> You have <span id="pendingTasks"></span> left </span>
    <button type="button" id="clear">Clear All</button>
  </div>
</div>

  • Related