scrimba
Shopping Checklist
Go Pro!Bootcamp

Bootcamp

Study group

Collaborate with peers in your dedicated #study-group channel.

Code reviews

Submit projects for review using the /review command in your #code-reviews channel

Shopping Checklist
AboutCommentsNotes
Shopping Checklist
Expand for more info
index.js
run
preview
console
const items = ["Candles", "Decorations", "Chocolate"]
const checklist = document.getElementById("checklist")
const form = document.getElementById('addItemForm');

// Task:
// - For each item in the items array, create a div with a class of "checklist-item", which contains a checkbox input and corresponding label.
// - Make sure that the shopping list can render a checkbox for all the items, even if new items are added to the items array.
for(let item of items) {
const checkListItem = createCheckListItem(item);
checklist.append(checkListItem);
}

function createCheckListItem(text) {
const randomNumber = Math.floor(Math.random()*1000000)
const id = 'item_' + randomNumber;
const checkListItem = document.createElement('div');
checkListItem.className = 'checklist-item';
const checkBoxInput = document.createElement('input');
checkBoxInput.setAttribute('type', 'checkbox');
checkBoxInput.setAttribute('id', id);
checkBoxInput.addEventListener('change', onCheckBoxChange);
const checkBoxLabel = document.createElement('label');
checkBoxLabel.setAttribute('for', id);
checkBoxLabel.innerText = text;
const deleteIcon = document.createElement('i');
deleteIcon.className = "fa fa-minus-circle";
deleteIcon.setAttribute("data-id", id);
deleteIcon.addEventListener("click", onDeleteItem);
checkListItem.append(checkBoxInput, checkBoxLabel, deleteIcon);
return checkListItem;
}

function onCheckBoxChange(e) {
const isChecked = e.target.checked;
const id = e.target.getAttribute('id');
const correspondingLabel = document.querySelector(`label[for='${id}']`);
correspondingLabel.className = isChecked ? 'strikethrough' : '';
}

function onDeleteItem(e) {
const id = e.target.dataset.id;
const checkbox = document.getElementById(id);
checkbox.removeEventListener('change', onCheckBoxChange);
this.removeEventListener('click', onDeleteItem);
checkbox.parentElement.remove();
const numberOfItems = checklist.childElementCount;
if(numberOfItems === 0)
checklist.innerHTML = "<p>No items to display.</p>"
}

form.addEventListener('submit', function(e) {
e.preventDefault();
const input = document.getElementById('enteredItem');
const enteredText = input.value;
const checkListItem = createCheckListItem(capitalize(enteredText));
input.value = "";
checklist.append(checkListItem);
const noItemsDisplay = document.querySelector('.checklist p');
if(noItemsDisplay)
noItemsDisplay.remove();
});

function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}

// Stretch goals:
// - Add an input which allows the user to add more items.
// - Add a delete button for the items.

Console
/index.html?
LIVE