Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to code a todo list in javascript, but somehow it doesn't work.

this is my JavaScript and HTML:

let todos = [] 
function createTodo() {
    let newTodo = {
        text: '',
        checked: 0
    }
    newTodo['text'] = prompt('Item description')
    todos.push(newTodo)
    
}

for (i in todos) {
    let listItem = document.createElement('li')
    let itemText = document.createTextNode(i['text'])
    console.log('itemText: ' + itemText)
    listItem.appendChild(itemText)
    console.log('listItem: ' + listItem)
    document.getElementById('todo-list').appendChild(listItem)
}
<!DOCTYPE html>
<html>
  <head>
    <title>TODO App</title>
    <link rel="stylesheet" type="text/css" href="./styles.css" />
  </head>
  <body>
    <div class="container center">
      <h1 class="center title">My TODO App</h1>
      <div class="flow-right controls">
        <span>Item count: <span id="item-count">0</span></span>
        <span>Unchecked count: <span id="unchecked-count">0</span></span>
      </div>
      <button class="button center" onClick="createTodo();">New TODO</button>
      <ul id="todo-list" class="todo-list">
      </ul>
    </div>
    <script src="./script.js"></script>
  </body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

As I can see in your code, there is nowhere to add created elements to HTML. And when it comes to open prompt, you should get value from the input.

This is how to get input value and reflects it to the HTML

let todos = []
function createTodo() {
    let newTodo = {
        text: '',
        checked: 0
    }
    newTodo['text'] = prompt('Item description')
    if( newTodo.text != null ) {
        todos.push(newTodo)
        reflectToHtml(newTodo)
    }
}
function reflectToHtml(i) {
    let listItem = document.createElement('li')
    let itemText = document.createTextNode(i['text'])
    listItem.appendChild(itemText)
    document.getElementById('todo-list').appendChild(listItem)
    document.getElementById('item-count').innerText = todos.length
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...