I’m trying to create a to-do list. I created a JavaScript code that appends the HTML tags in the list container. But how can I add the onclick property and text value of the input text next to the input checkbox?
<div id="to-do-list-container">
<h3>To do List</h3>
<ul id="list-items">
<li>
<div>
<input type="checkbox" class="list-item-checkbox" onclick="Check_item()">Item 1</input>
</div>
</li>
<li>
<div>
<input type="checkbox" class="list-item-checkbox" onclick="Check_item()">Item 2</input>
</div>
</li>
<li>
<div>
<input type="checkbox" class="list-item-checkbox" onclick="Check_item()">Item 3</input>
</div>
</li>
</ul>
<form action="javascript:void(0);">
<input type="text" id="list-item-input" placeholder="Enter item...">
<input type="submit" value="ADD" onclick="Add_item()">
</form>
</div>
function Add_item() {
var listItem = document.createElement("li");
var container = document.createElement("div");
var checkbox = document.createElement("input");
var itemName = document.getElementById("list-item-input");
itemName.value = "";
checkbox.type = "checkbox";
checkbox.className = "list-item-checkbox";
document.getElementById("list-items").appendChild(listItem);
listItem.appendChild(container);
container.appendChild(checkbox);
checkbox.appendChild(itemName.value);
};
2
Answers
so, if i understand, you should modify the code as follow:
In this modified version of Add_item(), a new element is created to hold the input text value and we set its textContent to the value of itemName. After using the itemName value, we delete it by setting it to an empty string to prepare for the next element input.
Note also that we assign the checkbox’s onclick property to the Check_item() function, to ensure that the function is executed when the checkbox is clicked.
You can use
Element#append
, which can insert text nodes. Moreover, you should setitemName.value
to an empty string only after adding the string to the container.addEventListener
can be used to add the click listener.