To-Do list saving items to database using ajax - javascript

I have a to-do list that kinda works, but when the page refreshed all of the added items get removed.
At first I tried using local storage to store and then retrieve the items, but I couldn't get that to work. Then I remembered about ajax, but I'm still a beginner and am not familiar with it.
I couldn't find a solution that works, but any tips would be much appreciated.
Html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css"
integrity="sha512-1PKOgIY59xJ8Co8+NE6FZ+LOAZKjy+KY8iq0G4B3CyeY6wYHN3yt9PW0XpSriVlkMXe40PTKnXrLnZ9+fkDaog=="
crossorigin="anonymous">
<title>Shopping List</title>
</head>
<body>
<a href="logout.php">
<button class="logout">Logout</button>
</a>
<header>
<h1>Shopping List</h1>
</header>
<form>
<input type="text" placeholder="Enter products" class="todo_input" />
<button class="todo_button" type="submit">
<i class="fas fa-plus-square"></i>
</button>
<div class="select">
<select name="todos" class="filter_todo">
<option value="all">All</option>
<option value="completed">In cart</option>
<option value="uncompleted">Not in cart</option>
</select>
</div>
</form>
<div class="todo_container">
<ul class="todo_list">
<div class="todo">
<li class="todo_item">Tomatoes</li>
<button class="complete_btn"><i class="fas fa-check"></i></button>
<button class="delete_btn"><i class="fas fa-trash"></i></button>
</div>
</ul>
</div>
<script src="script.js" type="application/javascript"></script>
</body>
</html>
Javascript:
//selectors
const todoInput = document.querySelector('.todo_input');
const todoButton = document.querySelector('.todo_button');
const todoList = document.querySelector('.todo_list');
const filterOption = document.querySelector('.filter_todo');
//event listeners
todoButton.addEventListener("click", addTodo)
todoList.addEventListener("click", deleteCheck)
filterOption.addEventListener("click", filterTodo)
//functions
function addTodo(event) {
event.preventDefault();
//todo DIV
const todoDiv = document.createElement('div');
todoDiv.classList.add('todo');
//todo LI
const newTodo = document.createElement('li');
newTodo.innerText = todoInput.value;
newTodo.classList.add('todo_item');
todoDiv.appendChild(newTodo);
if(todoInput.value === ""){
return null
}
//check mark BUTTON
const completedButton = document.createElement('button');
completedButton.innerHTML = '<i class="fas fa-check"></i>';
completedButton.classList.add('complete_btn')
todoDiv.appendChild(completedButton);
//delete BUTTON
const deleteButton = document.createElement('button');
deleteButton.innerHTML = '<i class="fas fa-trash"></i>';
deleteButton.classList.add('delete_btn')
todoDiv.appendChild(deleteButton);
//Append to Actual LIST
todoList.appendChild(todoDiv);
//Clear todo input VALUE
todoInput.value = ""
}
//DELETE & CHECK
function deleteCheck(e) {
const item = e.target;
//DELETE ITEM
if (item.classList[0] === "delete_btn") {
const todo = item.parentElement;
//ANIMATION TRANSITION
todo.classList.add("fall")
todo.addEventListener('transitionend', function () {
todo.remove()
})
}
//COMPLETE ITEM
if (item.classList[0] === "complete_btn") {
const todo = item.parentElement;
todo.classList.toggle("completedItem")
}
}
//FILTERING THE TASKS ACCORDING THE OPTION
function filterTodo(e) {
const todos = todoList.childNodes;
for(let i = 1; i<todos.length; i++ ){
switch (e.target.value) {
case "all":
todos[i].style.display = "flex";
break;
case "completed":
if (todos[i].classList.contains('completedItem')) {
todos[i].style.display = "flex";
} else {
todos[i].style.display = "none";
}
break;
case "uncompleted":
if (!todos[i].classList.contains('completedItem')) {
todos[i].style.display = "flex";
} else {
todos[i].style.display = "none";
}
break;
}
}
}

You can use ajax as an option to send requests to save your data in you Database and get your records to fill the list for example.
the syntax is a little bit simple:
var data = ($("#YOUR_HTML_FORM_ID").serialize());
$.ajax({
url: 'YOUR_API_ROUTE',
data: data,
processData: false,
type: 'POST',
success: function ( data ) {
// All good here, do something like show a success message
},
error: function (data) {
data = JSON.parse(data.responseText);
// something went wrong
}
});

Related

How to delete one button when deleting last to-do list item (JavaScript)

I'm creating a to-do list and I want my CLEAR ITEMS button to be deleted once I delete the last item on the list (now it doesn't disappear unless I refresh the page). How can I achieve this? Any suggestions? I've tried different solutions but I really don't know how to make it work. I'm really stuck at this.
JavaScript code:
const toDoItems = document.getElementsByClassName("to-do-items")[0];
const input = document.getElementById("input");
const trashIcon = document.getElementById("trash");
const delItems = document.getElementsByClassName("clear-items")[0];
input.addEventListener("keydown", function (event) {
if (event.key === "Enter") {
addItem();
clearItems();
}
});
function addItem() {
let divParent = document.createElement("div");
let divChild = document.createElement("div");
let checkIcon = document.createElement("i");
let trashIcon = document.createElement("i");
divParent.className = "item";
divParent.innerHTML = "<div>" + input.value + "</div>";
checkIcon.className = "fas fa-check-square";
checkIcon.style.color = "lightgray";
checkIcon.addEventListener("mouseenter", function () {
checkIcon.style.color = "limegreen";
});
checkIcon.addEventListener("mouseleave", function () {
checkIcon.style.color = "lightgray";
});
checkIcon.addEventListener("click", function () {
checkIcon.style.color = "green";
divParent.style.textDecoration = "line-through";
checkIcon.addEventListener("mouseleave", function () {
checkIcon.style.color = "green";
});
});
divChild.appendChild(checkIcon);
trashIcon.className = "fas fa-trash";
trashIcon.style.color = "darkgray";
trashIcon.addEventListener("mouseenter", function () {
trashIcon.style.color = "rgb(182, 71, 71)";
});
trashIcon.addEventListener("mouseleave", function () {
trashIcon.style.color = "darkgray";
});
trashIcon.addEventListener("click", function () {
divParent.remove();
if (toDoItems == 1) {
delItems.remove();
}
});
divChild.appendChild(trashIcon);
divParent.appendChild(divChild);
toDoItems.appendChild(divParent);
input.value = "";
}
let clearButton = false;
function clearItems() {
let clear = document.createElement("button");
if (clearButton === false) {
clear.innerHTML = "Clear Items";
clear.className = "btn";
delItems.appendChild(clear);
input.removeEventListener("click", clearItems);
}
clearButton = true;
document
.getElementsByTagName("button")[1]
.addEventListener("click", function () {
window.location.reload();
});
}
Here's the HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css"
integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
<title>To Do List</title>
</head>
<body>
<div class="container">
<div class="nav">
<h2><i class="fa-solid fa-clipboard-check"></i> To-do List</h2>
<div class="user-input">
<input id="input" type="text" /><button
onclick="addItem(), clearItems()"
>
Submit
</button>
</div>
</div>
</div>
<div class="container">
<div class="to-do-items"></div>
<div class="clear-items"></div>
</div>
<script src="script.js"></script>
</body>
</html>
Every time you delete something. Check how many items are left. If that amount is 0 remove the clear all button. If you press the clear all button. Make sure at the end of the code that clears all the items you also remove the button.
you can use element.remove() to get rid of the button. More info here.
I would also use document.getElementById() to get the button (maybe items too) itself. More info on that here.

How to put the edited contents on to do list

I'm a beginner web dev learner and I'm trying to create a to-do list app by vanilla JS.
I created some main functions but now I'm stucking in 2 points.
1st.
I created an "edit" button. this button adds input textbox element into li element that surrounds each to-do task by using a map method.However, I can't come up with a proper way to replace an original wrtten tasks with a text contents in input textboxes when I finish editing.
So, I would like you to tell me how to write a "compEdit" function in the source code below.
2nd
When I add several tasks and push an edit button of other than 1st task, too many input text boxes are created.Probably, the number of created textboxes is as same amount as the element in arrayItems.
I suppose using map method itself is a wrong aproach.But I can't come up with a good alternative.
I'll be glad if someone tell me a proper way and why the bug in 2nd question happens.
Source code is here
//grab the elements
const todoText = document.getElementsByClassName('todo-text')[0];
const todoBtn = document.getElementsByClassName('todo-btn')[0];
const inputTask = document.getElementsByClassName('input-task')[0];
const arrayItems = [];
//function to add tasks
const addTask = (task) => {
const listItem = document.createElement('li');
const showItem = inputTask.appendChild(listItem);
showItem.innerHTML = task;
listItem.classList.add('list-item');
arrayItems.push(listItem);
//create a delete button
const deleteBtn = document.createElement('button');
deleteBtn.innerHTML = 'delete';
listItem.appendChild(deleteBtn);
//call a function when the button will be clicked
deleteBtn.addEventListener('click', () => {
deleteTask(deleteBtn);
});
//create an edit button
const editBtn = document.createElement('button');
editBtn.innerHTML = 'edit';
listItem.appendChild(editBtn);
//call a function when the button will be clicked
editBtn.addEventListener('click', () => {
editTask(arrayItems, listItem);
});
};
const deleteTask = (deleteBtn) => {
const chosenItem = deleteBtn.closest('li');
inputTask.removeChild(chosenItem);
};
const editTask = (els = [], inputTask) => {
//create a textbox into list items
inputTask.innerHTML = els.map((el, i) => {
return `
<input type="text" class="editing-text[${i}]" name="item[${i}]" required>
<input type="submit" class="complete-btn" value="complete">
`
});
//grab the elements of "edit button" and text into it
const editingText = document.getElementsByClassName('editing-text')[0];
const compBtn = document.getElementsByClassName('complete-btn')[0];
//the function to complete editing
const compEdit = () => {
}
compBtn.addEventListener('click', compEdit);
}
todoBtn.addEventListener('click', () => {
const task = todoText.value;
if(task == ''){
return;
}
addTask(task);
todoText.value = '';
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<div class="wrap">
<header class="header">
<h1>Welcome!</h1>
</header>
<section class="add-todo">
<div class="list-title">
<h2>Add your task</h2>
</div>
<div class="contents-wrapper">
<div class="list-contents">
<input type="text" name="todo" class="todo-text">
<input type="submit" value="add" class="todo-btn">
</div>
</div>
</section>
<section class="current-tasks">
<div class="current-tasks__title">
<h3>current tasks</h3>
</div>
<div class="tasks-wrapper">
<ul class="input-task"></ul>
</div>
</section>
<footer></footer>
</div>
<script src="/main.js"></script>
</body>
</html>
When I add several tasks and push an edit button of other than 1st task, too many input text boxes are created
This is happening because as you add tasks, the number of elements are increasing, so the inputs are created on the basis of the number of li elements currently in the document. You can avoid this by using event.target which can be used to target each task element. I have shown an example with slight modification in your code.
//grab the elements
const todoText = document.getElementsByClassName("todo-text")[0];
const todoBtn = document.getElementsByClassName("todo-btn")[0];
const inputTask = document.getElementsByClassName("input-task")[0];
//function to add tasks
const addTask = (task) => {
const listItem = document.createElement("li");
const showItem = inputTask.appendChild(listItem);
const taskElem = document.createElement("span");
taskElem.innerHTML = task;
listItem.appendChild(taskElem);
listItem.classList.add("list-item");
//create a delete button
const deleteBtn = document.createElement("button");
deleteBtn.innerHTML = "delete";
listItem.appendChild(deleteBtn);
//call a function when the button will be clicked
deleteBtn.addEventListener("click", () => {
deleteTask(deleteBtn);
});
//create an edit button
const editBtn = document.createElement("button");
editBtn.innerHTML = "edit";
// add a class to identify
editBtn.classList.add("edit");
listItem.appendChild(editBtn);
//call a function when the button will be clicked
// editBtn.addEventListener("click", () => {
// // editTask(arrayItems, listItem);
// });
};
const deleteTask = (deleteBtn) => {
const chosenItem = deleteBtn.closest("li");
inputTask.removeChild(chosenItem);
};
inputTask.addEventListener("click", function(e) {
const target = e.target.classList.contains("edit"),
update = e.target.classList.contains("update");
if (target) {
let val = e.target.parentElement.firstChild.innerHTML;
// alert(val);
e.target.parentElement.innerHTML = `
<input type="text" name="todo" class="todo-text" value="${val}">
<input type="submit" value="update" class="todo-btn update">
`;
}
if (update) {
let updatedValue = e.target.previousElementSibling.value;
e.target.parentElement.innerHTML = `
<li class="list-item"><span>${updatedValue}</span><button>delete</button><button class="edit">edit</button></li>
`;
}
});
todoBtn.addEventListener("click", () => {
const task = todoText.value;
if (task == "") {
return;
}
addTask(task);
todoText.value = "";
});
<div class="wrap">
<header class="header">
<h1>Welcome!</h1>
</header>
<section class="add-todo">
<div class="list-title">
<h2>Add your task</h2>
</div>
<div class="contents-wrapper">
<div class="list-contents">
<input type="text" name="todo" class="todo-text">
<input type="submit" value="add" class="todo-btn">
</div>
</div>
</section>
<section class="current-tasks">
<div class="current-tasks__title">
<h3>current tasks</h3>
</div>
<div class="tasks-wrapper">
<ul class="input-task"></ul>
</div>
</section>
<footer></footer>
</div>

Delete button is not able to delete buttons. It is responsive in the console but nothing else

i'm having trouble using my delete button with my code. Instead of deleting an object, it creates a new one. code is under render items function. i've tried several things but it seems like my biggest problem is the placement of the rederItems function in the if statement. I also added the html to show you how that looks like too. Thanks!
// selectors
var nameOfItem = document.getElementById("nameOfItem");
var saveOfItem = document.getElementById("nameOfItem");
var shoppingList = document.getElementById("shoppingListContainer");
var nameArray = ["tea","bread","rice"]
// var nameArray = []
var setCart = [];
var getIngredientsForCart = localStorage.getItem
var emptyListText = document.getElementById("emptyList")
var removeButton = document.getElementById('removeItem');
var saveItems = document.getElementById("saveItems");
var cart = document.getElementById("shoppingListContainer")
cart.style.visibility = 'hidden';
saveItems.style.visibility = 'hidden'
saveItems.addEventListener('click', function() {
console.log('saved')
setCart.push(entry);
localStorage.setItem('cart', JSON.stringify(newArray));
});
/*
<li class="list-group-item" id="numberOfItems">1</li>
<li class="list-group-item" id="nameOfItem"></li>
<li class="list-group-item" id="removeItem"></li>
*/
// get from local storage
// var food = JSON.parse(localStorage.getItem("Ingredients"))
// console.log(food)
// nameArray = food
// --------------------------------
// render Item function
// --------------------------------
function renderItems() {
for (i = 0; i < nameArray.length; i++) {
var row = document.createElement("div");
row.setAttribute("class", "row");
var col2 = document.createElement("div");
var col3 = document.createElement("div");
col2.setAttribute("class", "col-8 item-name");
col3.setAttribute("class", "col-2 item-delete");
var newButton = document.createElement('button');
newButton.textContent = 'Delete';
newButton.setAttribute("data-item-idx", i);
newButton.addEventListener('click', function(event){
console.log(event.target.dataset.itemIdx)
var selectedItem = parseInt(event.target.dataset.itemIdx);
if(nameArray.splice(selectedItem, 1)){
console.log(nameArray)
renderItems()
}
})
col2.textContent = nameArray[i];
col3.appendChild(newButton);
row.appendChild(col2);
row.appendChild(col3);
shoppingList.appendChild(row);
}
}
// --------------------------------
// shopping Cart function
// --------------------------------
function shoppingCart() {
emptyListText.style.visibility = 'hidden';
cart.style.visibility = 'visible';
saveItems.style.visibility = 'visible'
renderItems()
}
// execute Function
shoppingCart()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous" />
<link href="https://fonts.googleapis.com/css?family=Open+Sans&display=swap" rel="stylesheet" />
<title>Meal Plan</title>
<link rel="stylesheet" href="../css/shoppinglist.css">
</head>
<body>
<div>
<h1>Shopping List</h1>
search recipes
</div>
<h1 id="emptyList">Cart is Empty :(</h1>
<section id="shoppingListContainer" class="container">
</section>
<button id="saveItems">Save Items</button>
</body>
<!-- <script src="/projects/mealPlan/assets/js/script.js"></script> -->
<script src="../js/shoppingList.js"></script>
</html>
You are calling renderItems() again on delete but you are never actually clearing the existing rendered html.
Simply adding shoppingList.innerHTML = ""; to the start of the renderItems() function will clear the html each time render runs.

How to set css style to local storage for dynamically created list using Javascript?

I've just started a Udemy course on Javascript, and the first project is to create a task list. I created it fine according the the tutorial but I wanted to add some features to it. when a new task gets added, I want to add the ability to mark it as complete.
I've been experimenting on how to do this using css (text-decoration: line-through) but have hit a dead end. Once the button to mark as "complete" is clicked a function is called that checks the list items for the class "check-item". I then add the class name "check-item-style" which applies the line-through to the clicked list item. If you could please help me to insert this into local storage and 'get' from local storage once the browser re-opens.
I'll try and keep the code as brief as possible. Only vanilla javascript if possible! I tried doing a code snippet but it wasn't working very well (maybe due to local storage not being available), so I have included shorted code below. Some of the code wasn't working without all the libraries so had to include sorry!
// Define UI Vars
const form = document.querySelector("#task-form");
const taskList = document.querySelector(".collection");
const taskInput = document.querySelector("#task");
//Event Listeners
form.addEventListener("submit", addTask);
taskList.addEventListener("click", checkTask);
document.addEventListener("DOMContentLoaded", getTasks);
function getTasks() {
if (localStorage.getItem("tasks") === null) {
tasks = [];
} else {
tasks = JSON.parse(localStorage.getItem("tasks"));
}
tasks.forEach(function(task) {
const li = document.createElement("li");
li.className = "collection-item";
li.appendChild(document.createTextNode(task));
const linkCheck = document.createElement("a");
linkCheck.className = "check-item secondary-content";
linkCheck.innerHTML = '<i class="fa fa-check"></i>';
li.appendChild(linkCheck);
taskList.appendChild(li);
});
}
function addTask(e) {
if (taskInput.value === "") {
alert("Add a task");
} else {
const li = document.createElement("li");
li.className = "collection-item";
li.appendChild(document.createTextNode(task));
const linkCheck = document.createElement("a");
linkCheck.className = "check-item secondary-content";
linkCheck.innerHTML = '<i class="fa fa-check"></i>';
li.appendChild(linkCheck);
taskList.appendChild(li);
storeTaskInLocalStorage(taskInput.value);
//Clear input
taskInput.value = "";
}
e.preventDefault();
}
function storeTaskInLocalStorage(task) {
let tasks;
if (localStorage.getItem("tasks") === null) {
tasks = [];
} else {
tasks = JSON.parse(localStorage.getItem("tasks"));
}
tasks.push(task);
localStorage.setItem("tasks", JSON.stringify(tasks));
}
function checkTask(e) {
let check = e.target.parentElement.parentElement;
if (e.target.parentElement.classList.contains("check-item")) {
check.className = "check-item-style";
addStylingToLocalStorage(check.className);
}
}
function addStylingToLocalStorage() {
//Please help here
}
.check-item-style {
text-decoration: line-through;
padding: 10px;
padding-right: 20px;
padding-left: 20px;
border-bottom: 1px solid rgba(0, 0, 0, 0.08);
margin: 0px;
}
<!DOCTYPE html>
<html lang="en">
<body>
<script
src="https://code.jquery.com/jquery-3.5.1.js"
integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
crossorigin="anonymous"
></script>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"
/>
<link
href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"
rel="stylesheet"
integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN"
crossorigin="anonymous"
/>
<title>Task List</title>
<link rel="stylesheet" href="stylesheet.css" />
<script src="app.js" defer></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"
defer
></script>
<div class="container">
<form id="task-form">
<div>
<input type="text" name="task" id="task" />
<label for="task">New Task</label>
</div>
<input type="submit" value="Add Task" class="btn" />
</form>
<div>
<ul class="collection"></ul>
</div>
</div>
</body>
</html>
There is an easy way of doing this without storing CSS In localStorage. Right now, if your list of tasks is Cleaning, Sleeping, and Reading, then you JSON looks like this:
[
"Cleaning",
"Sleeping",
"Reading"
]
Each item is just a string. If you want to keep track of what has already been checked, store and retrieve an array of objects from localStorage. This is an example JSON structure.
[
{
"name": "Cleaning",
"done": true
},
{
"name": "Sleeping",
"done": true
},
{
"name": "Reading",
"done": false
}
]
If you reload the page, you just need to style the tasks based on the done property.
Edit to your storing function:
function storeTaskInLocalStorage(task, done) {
let tasks;
if (localStorage.getItem('tasks') === null) {
tasks = [];
} else {
tasks = JSON.parse(localStorage.getItem('tasks'));
}
tasks.push({
name: task,
done: done
});
localStorage.setItem('tasks', JSON.stringify(tasks));
}

edit button input should be listed after clicking anything other on page

i made a to-do list and i am very new at this , but after adding multiple task it is adding in incomplete task and have one edit and delete button when trying to edit any list it is converting in type= text but when entering outside of this edit task it is still open to edit it should not be happening
here is java script code
var taskInput=document.getElementById("new-task");
var addButton=document.getElementsByTagName("button")[0];
var incompleteTaskHolder=document.getElementById("incomplete-tasks");
var completedTasksHolder=document.getElementById("completed-tasks");
var createNewTaskElement=function(taskString){
var listItem=document.createElement("li");
var checkBox=document.createElement("input");
var label=document.createElement("label");
var editInput=document.createElement("input");
var editButton=document.createElement("button");
var deleteButton=document.createElement("button");
label.innerText=taskString;
checkBox.type="checkbox";
editInput.type="text";
editButton.innerText="Edit";
editButton.className="edit";
deleteButton.innerText="Delete";
deleteButton.className="delete";
listItem.appendChild(checkBox);
listItem.appendChild(label);
listItem.appendChild(editInput);
listItem.appendChild(editButton);
listItem.appendChild(deleteButton);
return listItem;
}
var addTask=function(){
console.log("Add Task...");
if(taskInput.value==='')
{
alert('Required');
}
else
{
var listItem=createNewTaskElement(taskInput.value);
incompleteTaskHolder.appendChild(listItem);
bindTaskEvents(listItem, taskCompleted);
taskInput.value="";
}
}
var editTask=function(){
console.log("Edit Task...");
console.log("Change 'edit' to 'save'");
var listItem=this.parentNode;
var editInput=listItem.querySelector('input[type=text]');
var label=listItem.querySelector("label");
var containsClass=listItem.classList.contains("editMode");
if(containsClass){
if(listItem.value=='')
{
alert('empty edit');
}
else
{
label.innerText=editInput.value;
}
}else{
editInput.value=label.innerText;
}
listItem.classList.toggle("editMode");
}
var deleteTask=function(){
console.log("Delete Task...");
var listItem=this.parentNode;
var ul=listItem.parentNode;
ul.removeChild(listItem);
}
var taskCompleted=function(){
console.log("Complete Task...");
var listItem=this.parentNode;
completedTasksHolder.appendChild(listItem);
bindTaskEvents(listItem, taskIncomplete);
}
var taskIncomplete=function(){
console.log("Incomplete Task...");
var listItem=this.parentNode;
incompleteTaskHolder.appendChild(listItem);
bindTaskEvents(listItem,taskCompleted);
}
var ajaxRequest=function(){
console.log("AJAX Request");
}
//addButton.onclick=addTask;
addButton.addEventListener("click",addTask);
addButton.addEventListener("click",ajaxRequest);
$addNewTask.addEventListener("keypress",addTask);
var bindTaskEvents=function(taskListItem,checkBoxEventHandler){
console.log("bind list item events");
var checkBox=taskListItem.querySelector("input[type=checkbox]");
var editButton=taskListItem.querySelector("button.edit");
var deleteButton=taskListItem.querySelector("button.delete");
editButton.onclick=editTask;
deleteButton.onclick=deleteTask;
checkBox.onchange=checkBoxEventHandler;
}
for (var i=0; i<incompleteTaskHolder.children.length;i++){
bindTaskEvents(incompleteTaskHolder.children[i],taskCompleted);
}
for (var i=0; i<completedTasksHolder.children.length;i++){
bindTaskEvents(completedTasksHolder.children[i],taskIncomplete);
}
and here is html code where i am adding javascript
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Todo App</title>
<link rel="stylesheet" href="{{asset('css/style.css')}}">
<link rel="stylesheet" href="style.css" type="text/css" media="screen" charset="utf-8">
</head>
<body>
<div class="container">
<p>
<label for="new-task">Add List</label><input id="new-task" type="text" placeholder="Enter to do list"><button class="btn btn-default">Add</button>
</p>
<h3>To-do List</h3>
<ul id="incomplete-tasks">
</ul>
<h3>Completed Task</h3>
<ul id="completed-tasks">
</ul>
</div>
<script type="text/javascript" src="app.js"></script>
<script src="{{asset('js/index.js')}}"></script>
</body>
</html>
and here is attaching a image in which two edit input are showing and i want to when trying to do click anything other then edit should be listed , please help me
answer for your question in title
you should add id or unique identifier to that button and.
$(document).ready(()=>{
$(document.body).click((e)=>{
var button = $('#your_button_id')
if(e.target.id !== 'your_button_id' && $.contains(button[0]), e.target))
{
doSomething()
}
})
})

Categories