Checkbox List
The checkbox list can be used for a variety of different things. A key feature of this particulalr checkbox list is that when the website user 'ticks' items on the list, their completed items are saved in their web browser as local storage. Meaning that when they come back in future using the same web browser, items previously ticked are remembered. For a website author using WebYep CMS, items on the checkbox list are easily added, deleted or reordered. Name attributes applied to the checkboxes act as a unique IDs and are formed from short text elements. The checkbox labels use long text elements.
Example
HTML & PHP
<div class="check_list" data-checklist>
<?php foreach ((new WYLoopElement())->aLoopIDs("Checklist Items") as $webyep_oCurrentLoop->iLoopID) { $loopid=$webyep_oCurrentLoop->iLoopID; $_SESSION["loopid"]=$loopid; $webyep_oCurrentLoop->loopStart(false,$webyep_oCurrentLoop->iLoopID); // WebYepV2 ?>
<?php if(webyep_bIsEditMode() == true) : ?><hr><?php endif; ?>
<?php $webyep_oCurrentLoop->showEditButtons(true); // WebYepV1 ?>
<?php if(webyep_bIsEditMode() == true) : ?><br><?php endif; ?>
<?php if(webyep_bIsEditMode() == false) : ?>
<label>
<input type="checkbox" name="<?php endif; ?><?php webyep_shortText("Item Name", false, 550, 240); // WebYepV2 ?><?php if(webyep_bIsEditMode() == false) : ?>">
<span><?php endif; ?><?php if(webyep_bIsEditMode() == true) : ?><br><?php endif; ?><?php webyep_longText("Item Label", false, "", true, 600, 400); // WebYepV2 ?><?php if(webyep_bIsEditMode() == false) : ?></span>
</label><?php endif; ?>
<?php $webyep_oCurrentLoop->loopEnd(); } unset($_SESSION["loopid"]); // WebYepV2 ?>
</div>
CSS
.check_list {
border: 1px solid #ccc;
padding: 0 1rem;
margin: 1rem 0;
}
.check_list label {
display: flex;
align-content: center;
position: relative;
padding: 1rem 0;
border-bottom: 1px solid #ccc;
}
.check_list label:last-child {
border-bottom: none;
}
.check_list input[type="checkbox"] {
margin-right: 1rem;
}
.check_list span {
transition: opacity 300ms ease-in;
}
.check_list input[type="checkbox"]:checked + span {
text-decoration: line-through;
opacity: 0.5;
}
Javascript
const checkboxes = document.querySelectorAll('[data-checklist] input');
function storeItems() {
const checkedItems = [];
checkboxes.forEach((listitem) => {
if (listitem.checked) {
checkedItems.push({
checkboxName: listitem.name,
});
}
window.localStorage.setItem('checklist', JSON.stringify(checkedItems));
});
}
function readItems() {
const storage = window.localStorage.getItem('checklist');
if (storage) {
const checkedItems = JSON.parse(storage);
checkedItems.forEach((labelInStorage) => {
const matchingEl = document.querySelector(
`input[name="${labelInStorage.checkboxName}"]`
);
if (matchingEl) {
matchingEl.setAttribute('checked', true);
}
});
}
}
checkboxes.forEach((checkitem) =>
checkitem.addEventListener('change', storeItems)
);
readItems();