danilosilvadev / howtomakeaportfolio

If you are new at development and don't know what to do to demonstrate your skills this repo is to you :D
MIT License
37 stars 4 forks source link

Create the same todolist in react #3

Open danilosilvadev opened 6 years ago

danilosilvadev commented 6 years ago

HTML:

<body>
    <h1>Simple Todo List</h1>

    Name:
    <input id="formAdd" type="text" name="name">
    <button onclick="add()">Add</button>
    </br>
    <div id="todoList">
        <ul id="list">

        </ul>
    </div>

    <script src="todo.js"></script>
</body>

JS:

createLiElement = (value) => {
    const ul = document.getElementById("list");
    const li = document.createElement("li");
    const children = ul.children.length + 1;
    const buttonDelete = document.createElement("button");
    const buttonUpdate = document.createElement("button");
    buttonDelete.innerHTML = "Delete";
    buttonDelete.onclick = deleteBtn;
    buttonUpdate.innerHTML = "Update";
    document.getElementById("formAdd").value = '';
    buttonUpdate.onclick = (e, addEventListener) => updateBtn(closure(), e);
    li.setAttribute("id", children);
    const closure = () => {
        return {
            ul: ul,
            li: li,
            buttonDelete: buttonDelete,
            buttonUpdate: buttonUpdate
        }
    }
    li.appendChild(document.createTextNode(value + ' '));
    li.appendChild(buttonDelete);
    li.appendChild(buttonUpdate);
    ul.appendChild(li)
};

add = () => {
    const addValue = document.getElementById("formAdd").value;
    return (addValue === null || addValue === '') ? alert('Please fill this form') : createLiElement(addValue);
};

deleteBtn = (e) => {
    const liId = e.path[1].id;
    const elem = document.getElementById(liId);
    elem.parentNode.removeChild(elem);
};

updateBtn = (closure, e) => {
    const value = document.getElementById("formAdd").value;    
    return (value === null || value === '') ? alert('Write in the field!') : (() => {
        const liId = e.path[1].id;
        const elem = document.getElementById(liId);
        closure.buttonDelete.innerHTML = "Delete";
        closure.buttonDelete.onclick = deleteBtn;
        closure.buttonUpdate.innerHTML = "Update";
        const div = document.createElement("div");
        const item = closure.li.appendChild(div);
        item.setAttribute("id", liId);        
        div.appendChild(document.createTextNode(value + " "))
        div.appendChild(closure.buttonDelete);
        div.appendChild(closure.buttonUpdate);
        elem.parentNode.replaceChild(item, elem);
        document.getElementById("formAdd").value = '';      
        })();
};