<script>
var dataJSON = '';
var output = document.getElementById('output');
var todoList = document.querySelector('#todoList');
window.onload = function () {
if (sessionStorage['todolist'] != null) {
dataJSON = JSON.parse(sessionStorage['todolist']);
}
else {
var data = '[{"todo":"커피마시기","status":false},{"todo":"청소하기","status":false},{"todo":"운동하기","status":false},{"todo":"요리하기","status":false}]';
dataJSON = JSON.parse(data);
}
buildCheckboxes(dataJSON);
}
document.getElementById('myForm').addEventListener('submit', function (e) {
e.preventDefault();
var tempValue = document.querySelector('input[name="todo"]').value;
addNewItem({
"todo": tempValue
, "status": false
})
})
function addNewItem(data) {
addCheckbox(data, dataJSON.length);
dataJSON.push(data);
sessionStorage['todolist'] = JSON.stringify(dataJSON);
}
function addCheckbox(data, key) {
var li = document.createElement('li');
var checkbox = document.createElement('input')
var textInside = document.createTextNode(data.todo);
var span = document.createElement('span');
span.innerHTML = 'x';
span.onclick = remove;
checkbox.type = 'checkbox';
checkbox.value = key;
checkbox.checked = data.status;
checkbox.setAttribute('onchange', 'updateJSON()');
li.appendChild(textInside);
li.appendChild(checkbox);
li.appendChild(span);
document.querySelector('#todoList').appendChild(li);
}
function remove() {
var index = this.previousElementSibling.value;
console.log(index);
todoList.innerHTML = '';
dataJSON.splice(index, 1)
buildCheckboxes(dataJSON)
sessionStorage['todolist'] = JSON.stringify(dataJSON);
}
function buildCheckboxes(data) {
for (var key in data) {
addCheckbox(data[key], key)
}
}
function updateJSON() {
var key = event.target.value;
dataJSON[key].status = event.target.checked;
sessionStorage['todolist'] = JSON.stringify(dataJSON);
}
</script>
addEventListener
slice