Advertisement
Guest User

Jquery Issues

a guest
Aug 9th, 2012
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. window.addEventListener("DOMContentLoaded", function(){
  2.  
  3.     //getElementById Function
  4.     function g(x){
  5.         var theElement = document.getElementById(x);
  6.         return theElement;
  7.     }
  8.    
  9.     //Create select field element and populate with options.
  10.     function makeCats(){
  11.             var formTag = document.getElementsByTagName("form"), //formTag is an array of all the form tags.
  12.                 selectLi = g('select'),
  13.                 makeSelect = document.createElement('select');
  14.                 makeSelect.setAttribute("id", "groups");
  15.             for(var i=0, j=categoryLists.length; i<j; i++){
  16.                 var makeOption = document.createElement('option');
  17.                 var optText = categoryLists[i];
  18.                 makeOption.setAttribute("value", optText);
  19.                 makeOption.innerHTML = optText;
  20.                 makeSelect.appendChild(makeOption);
  21.             }
  22.             selectLi.appendChild(makeSelect);
  23.     }
  24.    
  25.     function getCheckboxVault(){
  26.         if(g('urgent').checked){
  27.             urgentValue = g('urgent').value;
  28.         }else{
  29.             urgentValue = "No";
  30.         }
  31.     }
  32.    
  33.     function toggleControls(n){
  34.         switch(n){
  35.             case "on":
  36.                 g('taskForm').style.display = "none";
  37.                 g('clear').style.display = "inline";
  38.                 g('displayLink').style.display = "none";
  39.                 g('addNew').style.display = "inline";
  40.                 break;
  41.             case "off":
  42.                 g('taskForm').style.display = "block";
  43.                 g('clear').style.display = "inline";
  44.                 g('displayLink').style.display = "inline";
  45.                 g('addNew').style.display = "none";
  46.                 g('items').style.display = "none";
  47.                 break;
  48.             default:
  49.                 return false;
  50.         }
  51.     }
  52.    
  53.     //Save data into local storage.
  54.     function storeData(key){
  55.         //If there is no key, this means this is a brand new item and we need a new key.
  56.         if(!key){
  57.             var id                  = Math.floor(Math.random()*100000001);
  58.         }else{
  59.             //Set the id to the existing key we're editing so that it will save over the data.
  60.             //The key is the same ky that's been passed along from the editSubmit event handler
  61.             //To the validate function, and then passed here, into the storeData function.
  62.             id = key;
  63.         }
  64.             //Gather up all our form field values and store in an object.
  65.             //Object properties are going to contain array with the form label and input value
  66.             getCheckboxVault();
  67.         var item                = {};
  68.             item.cats               = ["Category List: ", g("groups").value];
  69.             item.taskname           = ["My Task Name: ", g("taskname").value];
  70.             item.date               = ["Date: ", g("date").value];
  71.             item.time               = ["Time: ", g("time").value];
  72.             item.urgent             = ["Urgent: ", urgentValue];
  73.             item.slider1            = ["Estimated Time.", g("slider1").value];
  74.             item.textbox            = ["Notes: ", g("textbox").value];
  75.             //Save data into Local Storage: Use Stringify to convert our object to a string. Local storage only stores strings.
  76.             //Save form elements into LS
  77.             localStorage.setItem(id, JSON.stringify(item));
  78.             alert("Task Saved!");
  79. }
  80.  
  81.     function getData(){
  82.             toggleControls("on");  
  83.                 if(localStorage.length === 0){
  84.             alert("There are no task's to display. So default data was added.");
  85.             autoFillData();
  86.         }
  87.         //Write Data from Local Storage to the browser.
  88.         var makeDiv = document.createElement('div');
  89.         makeDiv.setAttribute("id", "items");
  90.         var makeList = document.createElement('ul');
  91.         makeDiv.appendChild(makeList);
  92.         document.body.appendChild(makeDiv);
  93.         g('items').style.display = "block";
  94.         for(var i=0, len=localStorage.length; i<len;i++){
  95.             var makeli = document.createElement('li');
  96.             var linksLi = document.createElement('li');
  97.             makeList.appendChild(makeli);
  98.             var key = localStorage.key(i);
  99.             var value = localStorage.getItem(key);
  100.             //Convert the string from local storage value back to an object by using JSON.parse()
  101.             var obj = JSON.parse(value);
  102.             var makeSubList = document.createElement('ul');
  103.             makeli.appendChild(makeSubList);
  104.             getImage(obj.cats[1], makeSubList);
  105.             for(var n in obj){
  106.                 var makeSubli = document.createElement('li');
  107.                 makeSubList.appendChild(makeSubli);
  108.                 var optSubText = obj[n][0]+" "+obj[n][1];
  109.                 makeSubli.innerHTML = optSubText;
  110.                 makeSubList.appendChild(linksLi);
  111.             }
  112.             makeItemLinks(localStorage.key(i), linksLi); //Create our edit and delete buttons/links for each item in local storage.
  113.         }
  114.    
  115.     }
  116.     //Get the image for the right category
  117.     function getImage(catName, makeSubList){
  118.         var imageLi = document.createElement('li');
  119.         makeSubList.appendChild(imageLi);
  120.         var newImg = document.createElement('img');
  121.         var setSrc = newImg.setAttribute("src", "images/"+ catName + ".png");
  122.         imageLi.appendChild(newImg);
  123.     }
  124.    
  125.     // Auto Populate Local Storage
  126.     function autoFillData(){
  127.         //The actual JSON OBJECT data required for this to work is coming from our json.js file, which is loaded from our HTML page.
  128.         //Store the JSON OBJECT into Local Storage.
  129.         for(var n in json){
  130.             var id = Math.floor(Math.random()*100000001);
  131.             localStorage.setItem(id, JSON.stringify(json[n]));
  132.         }
  133.     }
  134.  
  135.     //Make Item Links
  136.     //Create the edit and delete links for each storred item when displayed
  137.     function makeItemLinks(key, linksLi){
  138.         //add line break
  139.         var breakTag = document.createElement('br');
  140.         linksLi.appendChild(breakTag);
  141.        
  142.         //add edit single item link
  143.         var editLink = document.createElement('a');
  144.         editLink.href = "#";
  145.         editLink.key = key;
  146.         var editText = "Edit Task";
  147.         editLink.addEventListener("click", editItem);
  148.         editLink.innerHTML = editText;
  149.         linksLi.appendChild(editLink);
  150.        
  151.         //add line break
  152.         breakTag();
  153.         linksLi.appendChild(breakTag);
  154.        
  155.         //add delete single item link
  156.         var deleteLink = document.createElement('a');
  157.         deleteLink.href = "#";
  158.         deleteLink.key = key;
  159.         var deleteText = "Delete Task";
  160.         deleteLink.addEventListener("click", deleteItem);
  161.         deleteLink.innerHTML = deleteText;
  162.         linksLi.appendChild(deleteLink);
  163.        
  164.         //add horizontal line
  165.         var hrTag = document.createElement('hr');
  166.         linksLi.appendChild(hrTag);
  167.     }
  168.    
  169.     function editItem(){
  170.         //Grab the data from our item from Local Storage.
  171.         var value = localStorage.getItem(this.key);
  172.         var item = JSON.parse(value);
  173.        
  174.         //Show the form
  175.         toggleControls("off");
  176.        
  177.         //populate the form fields with current localStorage values.
  178.         g('groups').value = item.cats[1];
  179.         g('date').value = item.date[1];
  180.         g('time').value = item.time[1];
  181.         if(item.urgent[1] == "on"){
  182.         g('urgent').setAttribute("checked", "checked");
  183.         }
  184.         g('slider1').value = item.slider1[1];
  185.         g('date').value = item.date[1];
  186.         g('textbox').value = item.textbox[1];
  187.         g('time').value = item.time[1];
  188.         g('taskname').value = item.taskname[1];
  189.    
  190.         //Remove the initial listener from the input 'save contact button'
  191.         save.removeEventListener("click", storeData);
  192.         //Change the submit button Value to Edit Button
  193.         g('submit').value = "Edit Task";
  194.         var editSubmit = g('submit');
  195.         //Save the key value established in this function as a property of the editSubmit event
  196.         //so we can use that value when we save the data we edited.
  197.         editSubmit.addEventListener("click", validate);
  198.         editSubmit.key = this.key;
  199.    
  200.     }
  201.  
  202.     function deleteItem(){
  203.         var ask = confirm("Are you sure you want to delete this task?");
  204.         if(ask){
  205.             localStorage.removeItem(this.key);
  206.             window.location.reload();
  207.         }else{
  208.             alert("Task was not deleted!");
  209.        
  210.         }
  211.     }
  212.  
  213.     function clearLocal(){
  214.         if(localStorage.length === 0){
  215.             alert("There is no data to clear.");
  216.         }else{ 
  217.             localStorage.clear();
  218.             alert("All tasks deleted!");
  219.             window.location.reload();
  220.             return false;
  221.         }
  222.     }
  223.    
  224.     function validate(eData){
  225.         //Define the elements we want to check
  226.         var getCats = g('groups');
  227.         var getTaskName = g('taskname');
  228.         var getDate = g('date');
  229.         var getTime = g('time');
  230.        
  231.         //Reset Error Messages
  232.         errMsg.innerHTML = "";
  233.         getCats.style.border = "1px solid black";
  234.         getTaskName.style.border = "1px solid black";
  235.         getDate.style.border = "1px solid black";
  236.         getTime.style.border = "1px solid black";
  237.  
  238.    
  239.         //Get Error Messages
  240.         var messageAry = [];
  241.        
  242.         //Cats Validation
  243.         if(getCats.value === "--Choose A Category--"){
  244.             var catsError = "Please choose a category.";
  245.             getCats.style.border = "1px solid red";
  246.             messageAry.push(catsError);
  247.         }
  248.        
  249.         //Task Name Validation
  250.         if(getTaskName.value === ''){
  251.             var tNameError = "Please enter a task name.";
  252.             getTaskName.style.border = "1px solid red";
  253.             messageAry.push(tNameError);
  254.         }
  255.        
  256.         //Date Validation
  257.         if(getDate.value === ''){
  258.             var dateError = "Please enter the date the task is due on.";
  259.             getDate.style.border = "1px solid red";
  260.             messageAry.push(dateError);
  261.         }
  262.        
  263.         //Time Validation
  264.         if(getTime.value === ''){
  265.             var timeError = "Please enter the time of day the task is due on.";
  266.             getTime.style.border = "1px solid red";
  267.             messageAry.push(timeError);
  268.         }
  269.        
  270.         //If there were errors, display them on screen.
  271.         if(messageAry.length >= 1){
  272.             for(var i=0, j=messageAry.length; i < j; i++){
  273.                 var txt = document.createElement('li');
  274.                 txt.innerHTML = messageAry[i];
  275.                 errMsg.appendChild(txt);
  276.             }
  277.             eData.preventDefault();
  278.         return false;
  279.         }else{
  280.             //If all req info is supplied save our data! Send the key value (which came from the editData function).
  281.             //Remember this key value was passed through the editSubmit event listener as a property.
  282.             storeData(this.key);
  283.         }
  284.  
  285.     }
  286.     //Variable defaults
  287.     var categoryLists = ["--Choose A Category--", "Personal", "School", "Grocery", "Work", "Misc"],
  288.         urgentValue = "No",
  289.         errMsg = g('errors');
  290.     ;
  291.     makeCats();
  292.    
  293.     //Set Link & ubmit Click Events
  294.    
  295.     var displayLink = g('displayLink');
  296.     displayLink.addEventListener("click", getData);
  297.     var clearLink = g("clear");
  298.     clearLink.addEventListener("click", clearLocal);
  299.     var save = g("submit");
  300.     save.addEventListener("click", validate);
  301.    
  302.  
  303.    
  304.  
  305. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement