Home > Software engineering >  Problems with javascript html dom
Problems with javascript html dom

Time:09-18

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)
  }
}
<!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>

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

CodePudding user response:

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(){
    
    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="";

}

CodePudding user response:

If you need list of p

let tasks = []

  function addV() {
    let x = document.getElementById("bara")
    tasks.push(x.value)
    const instance = document.getElementById("t")
    instance.innerHTML = '';
    for (let i = 0; i < tasks.length; i  ) {
      const p = document.createElement("p");

      p.innerText  = tasks[i];
      instance.appendChild(p);
    }

  }
  • Related