PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, May 12, 2022

[FIXED] How can I append a checkbox input wrapped by the 'li'?

 May 12, 2022     append, javascript, list     No comments   

Issue

I managed to input the 'li' inside the 'ul', but I need to have a checkbox input inside the li, and I can't seem to figure how.

<body>
    <div class="card">
        
        <h1>To-do list</h1>
        
        <input type="text" id="taskInput" placeholder="Digite aqui sua tarefa">
        <button id="add">Adicionar</button>
        
        <ul id='tasks'>
            <li><input type="checkbox"> Tarefa 1</li>
        </ul>
        
    </div>
    <script>

      document.getElementById('add').onclick = function add() {

        const val = document.querySelector('input').value;
        const ul = document.getElementById('tasks');
        let li = document.createElement('li');
    
        li.appendChild(document.createTextNode(val));
        ul.appendChild(li);
      };

    </script>
</body>

Solution

Try to create element input and specify the type to checkbox and added it to created element li first, then add the text value of input also lastly append it to ul:

    document.getElementById("add").onclick = function () {
      const val = document.querySelector("#taskInput").value; //specify the selector
      const ul = document.getElementById("tasks");
      let li = document.createElement("li");

      let input = document.createElement("input"); //add Input
      input.type = "checkbox"; //specify the type of input to checkbox
      li.appendChild(input);
      li.appendChild(document.createTextNode(val));
      ul.appendChild(li);
    };
  <div class="card">
    <h1>To-do list</h1>

    <input type="text" id="taskInput" placeholder="Digite aqui sua tarefa" />
    <button id="add">Adicionar</button>

    <ul id="tasks">
      <li><input type="checkbox" /> Tarefa 1</li>
    </ul>
  </div>



Answered By - TAHER El Mehdi
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing