I am unable to show my input through html but it shows through console.log(). It is not showing up below on my list. My delete button also is not working as well. Not sure what is going on.
$(document).ready(function(){
$('#addButton').click(function(){
var task = $(".note").val();
console.log(task);
$(".todo-list").append('<li><div class ="button-center"><button id="delButton">Delete</button><button id="editButtton">Edit</button></div></li>');
});
});
$('#delButton').click(function(){
var deleteNote = $('ul').children().length;
$('ul').children()[deleteNote - 1].remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<header data-role="header"><h1>To Do List</h1>
<a href="#">Home</a>
</header>
<div role="main" class="todo-container">
<div class="input">
<input type="text" class="note" placeholder="Input new note..">
<button id="addButton">Add</button>
</div>
</div>
<ul class="todo-list">
<li>
<div class ="button-center">
<button id="delButton">Delete</button>
<button id="editButtton">Edit</button>
</div>
</li>
</ul>
</body>
In the solution below, the task content is dynamically inserted into the HTML code; the easiest way to do this is to use `${variable}`. Improved the click event to delete the related <li> element when the delete <button> is clicked.
$(document).ready(function(){
$('#addButton').click(function() {
var task = $(".note").val();
/* New <li> should not be added when task is not entered. */
if(task.length == 0) {
alert("Please enter a task.");
return;
}
/* Task content is added to dynamic content. */
$(".todo-list").append(`<li><span>Task: ${task}</span><div class="button-center"><button class="deleteButton">Delete</button><button class="editButtton">Edit</button></div></li>`);
/* After clicking the Add button, the <input> element is cleared. */
$(".note").val("");
});
/* Fires when clicking the <button> element with the ".deleteButton" class style applied. */
$(document).on('click', '.deleteButton', function () {
/* The two parents of the <button> element are the <li> element. */
$(this).parent().parent().remove();
});
});
* {
box-sizing: border-box;
}
ul {
margin: 0;
padding: 0;
}
ul li {
cursor: pointer;
position: relative;
background: #eee;
font-size: 18px;
transition: 0.2s;
user-select: none;
}
ul li:nth-child(odd) {
background: #f9f9f9;
}
ul li:hover {
background: #ddd;
}
button {
margin-right: 10px;
}
<!-- jQuery Reference -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div role="main" class="todo-container">
<div class="input">
<input type="text" class="note" placeholder="Input new note..">
<button id="addButton">Add</button>
</div>
<ul class="todo-list"></ul>
</div>