I'm trying to make a pretty simple to-do list. You type in something, it gets added to the list and stored in the local storage. My next step is adding a button next to each list item that I could then use to individually delete things as opposed to deleting the whole list. I've found a couple of SO questions about making buttons with jQuery and tried to follow them, but something isn't working right because I'm not getting the right output. Here's the code:
<!DOCTYPE html>
<!--Project-->
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
let list = [];
if (localStorage.getItem("mylist") != null) {
let array = JSON.parse(localStorage.getItem("mylist"));
for (let element of array) {
list.push(element);
$('#list').append('<li>' + element + '</li>');
}
}
$('button').click(function() {
if ((this.id) == "add") {
let input = $('#input').val();
// making button?
let button = $('<button/>', {type:'button', id:input, text:'Delete'});
// appending text and button?
$('#list').append('<li>' + input + button + '</li>');
list.push(input);
let json = JSON.stringify(list);
localStorage.setItem("mylist", json);
$('#input').val('');
}
else {
localStorage.clear();
$("#list").empty();
}
event.preventDefault();
});
});
</script>
</head>
<body>
<form>
<input type="text" id="input" placeholder="Enter tasks...">
<button id="add">Add</button>
<button id="delete">Delete All</button>
<br>
<ul id="list">
</ul>
</form>
</body>
</html>
For some reason, I'm just getting the text from the input box and [object Object] next to that. I'm not really sure what to do as I'm having trouble finding documentation on how to create elements in this way using jQuery. I'm trying to create a button that has an ID that matches the text that was put into the text box, that way I can later reference that ID and use it to delete stuff. Maybe there's another way I should be going about this? Any help is appreciated.