[SOLVED] Problems with javascript html dom

Issue

This Content is from Stack Overflow. Question asked by MarNavuu

html

<!DOCTYPE html>
<html>
    <head>
        <title>To Do</title>
    </head>
<body>
<script src="motor.js"></script>
<p>Task</p>
<input type="search" placeholder="task" id="bara">
<button onclick="addV()">ADD</button>
<hr>
<h1>TO DO TASKS</h1>
<p id="t"></p>
</body>
</html>

js


let tasks = []

function addV(){
    
    let x = document.getElementById("bara")
    tasks.push(x.value)
    document.getElementById("t").textContent = " " 
    for(let i = 0;i<tasks.length;i++){
    

    const p = document.createElement("p");
    
    p.innerText += tasks[i]
    document.body.append(p)
    console.log(tasks)
    
    }
}

Basically i have this problem when i hit my add button second time it add again the first element from the array butt how do i manage to show only the last element without the first one in the next p elements when i hit add button



Solution

If I understand your need correctly, you do not want to "repeat" displaying "task" entered previously (which will result in displaying previous input tasks multiple times) when you perform entering new task(s).

In that case, please clear the element "t" before you update it.

So the HTML is

<!DOCTYPE html>
<html>
    <head>
        <title>To Do</title>
    </head>
<body>
<script src="motor.js"></script>
<p>Task</p>
<input type="search" placeholder="enter the task" id="bara">
<button onclick="addV()">ADD</button>
<hr>
<h1>TO DO TASKS</h1>
<div id="t"></div>
</body>
</html>

and the JS (motor.js) is

let tasks = []

function addV(){
  if (document.getElementById("bara").value !=""){
    let x = document.getElementById("bara")
    tasks.push(x.value)
    document.getElementById("t").textContent = " " 

    var tempstring=""
     for(let i = 0;i<tasks.length;i++){

      tempstring=tempstring +"<br>"+ tasks[i];
    
      //const p = document.createElement("p");
      //    p.innerText += tasks[i]
      //    document.body.append(p)  
      }

    document.getElementById("t").innerHTML=tempstring;
    document.getElementById("bara").value="";
  }
}


This Question was asked in StackOverflow by MarNavuu and Answered by Ken Lee It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?