Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function solve() {
- const main = document.querySelector('main');
- // eventListener on the whole page!
- main.addEventListener('click', (e) => {
- if (e.target.textContent === 'Add') {
- add(e);
- }
- if (e.target.textContent === "Del") {
- del(e);
- }
- });
- // delete
- function del(e) {
- e.preventDefault();
- let li = e.target.parentNode;
- let ul = li.parentNode;
- let module = ul.parentNode;
- li.remove();
- if(ul.children.length === 0){
- module.remove();
- }
- }
- function add(e) {
- e.preventDefault();
- let lecture = document.querySelector('input[name="lecture-name"]');
- let date = document.querySelector('input[name="lecture-date"]');
- let module = document.querySelector('select[name="lecture-module"]');
- // verify input
- if (lecture.value.trim() === "" || module.value.trim() === 'Select module' || module.value.trim() === "" ||
- date.value.trim() === "") {
- return;
- }
- let parsedDate = date.value.split('-').join("/").split('T').join(' - ');
- // adding element
- let div = document.querySelector('.modules');
- let innerDiv = Array.from(document.querySelectorAll('.modules>div>h3'));
- let isPresented = false;
- let ul = undefined; // Check if it is added already
- for (let i = 0; i < innerDiv.length; i++) {
- if (innerDiv[i].textContent === module.value.toUpperCase() + '-MODULE') {
- isPresented = true;
- ul = innerDiv[i].parentNode.children[1];
- break;
- }
- }
- if (!isPresented) { // if not added -> add
- let htmlString = `<div class = "module">
- <h3>${module.value.toUpperCase()}-MODULE</h3>
- <ul>
- <li class="flex">
- <h4>${lecture.value} - ${parsedDate}</h4>
- <button class="red">Del</button>
- </li>
- </ul>
- </div>`;
- div.insertAdjacentHTML("beforeend", htmlString);
- } else { // it it is add
- let liHtml = `<li class="flex">
- <h4>${lecture.value} - ${parsedDate}</h4>
- <button class="red">Del</button>
- </li>`;
- ul.insertAdjacentHTML("beforeend", liHtml);
- // SORTING
- function sortList(ul) {
- let new_ul = ul.cloneNode(false);
- // Add all lis to an array
- let lis = [];
- for (let i = ul.childNodes.length; i--;) {
- if (ul.childNodes[i].nodeName === 'LI')
- lis.push(ul.childNodes[i]);
- }
- // Sort the lis in descending order
- lis.sort((a, b) => a.children[0].textContent.slice(-18).localeCompare(b.children[0].textContent.slice(-18)))
- // Add them into the ul in order
- for (let i = 0; i < lis.length; i++)
- new_ul.appendChild(lis[i]);
- ul.parentNode.replaceChild(new_ul, ul);
- }
- sortList(ul)
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement