ToDoList with JQuery and HTML5 Localstorage

Today i will show you ToDoList using jQuery, HTML5 Localstorage.
This is the script

document.getElementById('myForm').addEventListener('submit',saveToDo);
function saveToDo(e){
	elementValue = document.getElementById('todoId').value;
	if(!elementValue){
		alert("You must enter a value in the New Task field")
		return false;
	}
	var todo = {
		name:elementValue
	}
	if(localStorage.getItem('todoList') === null){
		var todos =[];
		todos.push(todo);
		localStorage.setItem('todoList',JSON.stringify(todos))
	}
	else{
		var todos = JSON.parse(localStorage.getItem('todoList'));
		todos.push(todo);
		localStorage.setItem('todoList',JSON.stringify(todos))
	}
	showToDoList()
e.preventDefault()
}
function showToDoList(){
	var todos = JSON.parse(localStorage.getItem('todoList'));
	var output ='';
	for(var i=0; i < todos.length; i++){
		var name = todos[i].name;
		output +='<li class="list-group-item">'+
		'<input type="text" class="form-control" style="margin-bottom:10px;" value="'+ name +'"> '+
		'Update  ' +
		'Delete' +
		 '</li>'
	}
	document.getElementById('result').innerHTML = output;
}
function deletetodo(id){
		var todos = JSON.parse(localStorage.getItem('todoList'));
		for(var i=0; i < todos.length; i++){
			var name = todos[i].name;
			if(name === id){
				todos.splice(i,1)	
			}
		localStorage.setItem('todoList',JSON.stringify(todos));
		showToDoList();
	}
}
function updatetoDo(name){
  var newValue = $('#result').find('a[data-value="' + name+'"]').prev('input').val();
  var todos = JSON.parse(localStorage.getItem('todoList'));
  for(var i =0;i < todos.length;i++){
    if(todos[i].name == name){
      todos[i].name = newValue;
    }
  }
  localStorage.setItem('todoList', JSON.stringify(todos));
  showToDoList();
}

This is HTML for ToDoList


  <!DOCTYPE html>
<html lang="en">
  <head>
    
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
   <link href="bootstrap.min.css" rel="stylesheet">

   <link href="style.css" rel="stylesheet">


  </head>
  <body onload="showToDoList()">
  <div class="container">
 <form id="myForm" class="form-inline">
    <div class="form-group">
    <input type="text" class="form-control" id="todoId" placeholder="Enter To Do List">
  </div>
  <button type="submit" class="btn btn-primary">Add To Do List</button>
</form>

  <div id="result" class="list-group">
  


</div>
</div>
<script
  src="https://code.jquery.com/jquery-3.2.0.slim.min.js"
  integrity="sha256-qLAv0kBAihcHZLI3fv3WITKeRsUX27hd6upBBa0MSow="
  crossorigin="anonymous"></script>

<script src="app.js"> </script>
  </body>
</html>

Demo

Leave a Reply

Your email address will not be published. Required fields are marked *