childNode.remove() doesn't seem to be working - javascript

I'm writing a google sheets add on that helps you track data as you play a game. In the sidebar, you can search for a monster in the game and after you hit the submit button the monster's stats, a list of what items they drop after a kill, and a link to the wiki is rendered on screen.
The problem I'm having is that when you search a new monster after having already searched for one, the old items from the drop section won't get removed. The other sections on stats and the wiki link will change, but instead of removing the old drop items, the new items just get added to the end of the list.
I've tried using parent.removeChild() and childNode.remove() and neither seem to do anything and I'm wondering if its because of how google apps script works.
Here is the html for the sidebar itself: note that include() is a custom function that google recommends you add to your script so you can import other files.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include('Info sidebar styles'); ?>
</head>
<body>
<form id="monsters">
<input class="monsterInput" type="text"placeholder="Monster Name" name="monsterName" />
<input class="monsterInput" type="text" placeholder="Monster Level" name="monsterLvl" />
<button id="submit">Search</button>
</form>
<div id="output">
</div>
<?!= include('sidebar script'); ?>
</body>
</html>
Here's the code for sidebar script:
<script>
if (document.readyState == 'loading') {
document.addEventListener('DOMContentLoaded', ready)
} else {
ready()
}
function ready(){
// create the divs that are later filled with info
var output = document.getElementById("output");
var stats = document.createElement("div");
stats.id = "statsDiv";
var drops = document.createElement("div");
drops.id = 'dropDiv';
var list = document.createElement("div");
list.id = "dropList";
var wiki = document.createElement("div");
wiki.id = "wiki";
output.appendChild(stats);
output.appendChild(drops);
output.appendChild(wiki);
var index = 0;
// the onSuccess for the onClick eventHandler. data is an object returned from the function call below
function onSuccess(data) {
console.log(`first index ${index}`);
// if the submit button has already been pushed and added the droplist to the DOM, increase the index
if(drops.getElementsByClassName("dropItem")[0]){
index++;
console.log(`second index ${index}`);
};
console.log(index);
// get the stats
var hitpoints = data.hitpoints;
var attackarray = data["attack_type"]
var attackTypes = '';
var attack1 = attackarray[0];
var attack2 = attackarray[1];
var attack3 = attackarray[2];
var attack4 = attackarray[3];
if(attackarray.length === 1){
attackTypes = attack1;
} else if (attackarray.length === 2){
attackTypes = `${attack1}, ${attack2}`;
} else if (attackarray.length === 3){
attackTypes = `${attack1}, ${attack2}, ${attack3}`;
} else if (attackarray.length === 4){
attackTypes = `${attack1}, ${attack2}, ${attack2}, ${attack4}`;
}
var attLvl = data["attack_level"];
var defLvl = data["defence_level"];
var magicLvl = data["magic_level"];
var rangeLvl = data["ranged_level"];
var maxHit = data["max_hit"];
var aggro = '';
if(data.aggressive){
aggro = "Yes";
} else {
aggro = "No";
}
var speed = data["attack_speed"];
// put the stats into html form
var statsInner =
`<h2> Stats </h2>
<ul id="statsList">
<li>Hitpoints: ${hitpoints}</li>
<li>Attack Level: ${attLvl}</li>
<li>Defense Level: ${defLvl}</li>
<li>Magic Level: ${magicLvl}</li>
<li>Ranged Level: ${rangeLvl}</li>
<li>Attack Style: ${attackTypes} </li>
<li>Attack Speed: ${speed}</li>
<li>Max Hit: ${maxHit} </li>
<li>Aggressive? ${aggro} </li>
</ul>`;
stats.innerHTML = statsInner;
drops.innerHTML = '<h2>Drops</h2>';
// Put the wiki url into HTML
var wikiURL = data["wiki_url"];
var wikiInner = `<p>For more info check out this monsters page on the wiki, <a href=${wikiURL}>here</a>.</p>`;
wiki.innerHTML = wikiInner;
// get the drop information and put it in html form. make the data-id attribute of each object equal the value of index
data.drops.forEach(function (item) {
var name = item.name;
var quant = item.quantity;
var members = '';
if(item.members){
members = "(m)";
}
var nameQM = `${name} (x${quant}) ${members}`;
var rarity = (item.rarity) * 100;
var rare = rarity.toFixed(2);
var nameNode = document.createElement("div");
var itemList =
`<p>${nameQM}</p>
<br>
<p> Rarity: ${rare} percent </p>`;
nameNode.innerHTML = itemList;
nameNode.className = "dropItem";
nameNode.dataset.id = index;
list.appendChild(nameNode);
})
drops.appendChild(list);
// if the drop item has a data-id that doesn't match the current index, remove it from the DOM.
var dropArray = list.getElementsByClassName("dropItem");
for(var i = 0; i < dropArray.length; i++){
var item = dropArray[i];
if(item.dataset.id != index){
item.remove();
}
}
}
//add the event listener to the submit button. getMonsterData makes an API call, parses the data, and returns an object filled with the data we add to the DOM through the success handler
document.getElementById("submit").addEventListener("click", function (e) {
e.preventDefault();
var parent = e.target.parentElement;
var monsterName = parent.elements[0].value;
var monsterlvl = parent.elements[1].value;
google.script.run.withSuccessHandler(onSuccess).getMonsterData(monsterName, monsterlvl);
});
}
</script>

Related

Javascript / CSS How to make several div elements with different data that are entered into the same input form

How does one create a new div through the input form (using the
button) a div appears with the data that was entered last?
I want to create a new div with data from input form.
Next I want to create a new div using the same. But using a new data record only for the first div and another that i created div's doesn't have any data.
How do I go about making that new input = new div+new data from this input&
let infoData = {
budget: 0,
expenses: 0,
balance: 0,
expenseObj: {
name: "",
amount: 0
},
budgetSubmit: function() {
infoData.budget = parseInt(document.getElementById('budget-input').value);
budgetAmount = infoData.budget;
document.getElementById('budget-amount').innerHTML=budgetAmount;
},
expenseSubmit: function() {
infoData.expenses = parseInt(document.getElementById('expense-input').value);
expenseName = document.getElementById('expense-name').value;
infoData.expenseObj.name = expenseName;
expenseAmount = infoData.expenses;
infoData.expenseObj.amount = expenseAmount;
document.getElementById('expense-amount').innerHTML=expenseAmount;
},
balanceSubmit: function() {
infoData.balance = infoData.budget;
balanceAmount = infoData.balance;
document.getElementById('balance-amount').innerHTML=balanceAmount;
}
}
calcBtn.addEventListener('click', function() {
infoData.budgetSubmit();
infoData.balanceSubmit();
});
addExpBtn.addEventListener('click', function() {
infoData.expenseSubmit();
});
addExpBtn.addEventListener('click', function(event) {
balanceAmount = balanceAmount - expenseAmount;
document.getElementById('balance-amount').innerHTML=balanceAmount;
});
let divEvent = document.getElementById('expense-row');
if (typeof(divEvent) !== "undefined") {
addExpBtn.addEventListener('click', function(event) {
const divExpense = document.createElement('div');
divExpense.className = 'div-expense';
divExpense.innerHTML = `
<p>
<b class="text-uppercase">name: </b><span id="div-expense-name">Name</span>
</p>
<p>
<b class="text-uppercase">amount: </b><span id="div-expense-amount">0</span>₴
</p>
<p>
<span id="div-expense-delete">Delete</span>
</p>`;
document.getElementById('expense-row').appendChild(divExpense);
document.getElementById('div-expense-name').innerHTML=infoData.expenseObj.name;
document.getElementById('div-expense-amount').innerHTML=infoData.expenseObj.amount;
});
}
You will have to create the div when you press the button, you could do this:
$("button").click(function(){
const newDiv = document.createElement("div");
const newDivText = document.createTextNode("");
$(newDivText).append($("input").val());
$(newDiv).append(newDivText);
$(document).append(newDiv);
});
I think that is what you're after. If you need any explanation, let me know.
function addDiv(event){
event.preventDefault();
var input= document.getElementsByTagName("input")[0];
var div = document.createElement('div');
div.innerHTML = input.value;
document.body.appendChild(div);
input.value='';
}
<form action ="#">
<input type=text/>
<button onclick='addDiv(event)'type='submit'>Submit</button>
</form>

Attaching Event to dynamically created element

I am working at my 'To Do List'. My goal is to create an 'delete' button inside previously created div, which contains note written by user.
The problem is that I can't use Jquery - click() because it doesn't work with dynamically created elements.
I tried to use on(), but it causes that 'delete' button appears in every note I made.
var ammleng;
var amount = [];
function ammcheck() {
if (amount.length == 0) {
return amount.length;
} else {
return amount.length++;
}
}
function Start() {
var start = document.getElementsByClassName('start')[0];
start.style.display = 'none';
var textarea = document.getElementsByClassName('textarea')[0];
textarea.classList.remove('locked');
var btn = document.getElementsByClassName('btn__container')[0];
btn.classList.remove('locked');
var text = document.getElementsByClassName('text')[0];
text.classList.add('after');
$('.notes').slideDown(2000);
}
function add() {
var txtarea = document.getElementsByClassName('textarea')[0];
ammleng = amount.length;
if (ammleng >= 13) {
alert('Za dużo notatek!')
} else if (txtarea.innerText.length < 1) {
alert('Nic nie napisałeś :(');
} else {
amount[ammcheck()] = document.getElementsByClassName('note');
var text = $('.textarea').html();
var cont = document.getElementsByClassName('notes')[0];
var ad = document.createElement('div');
var adding = cont.appendChild(ad);
adding.classList.add('note');
adding.innerText = text;
txtarea.innerText = '';
}
}
function reset() {
var els = document.getElementsByClassName('notes')[0];
els.innerHTML = '';
amount = [];
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='content'>
<div class='logo'>
To Do List
</div>
<div class='text'>
<button class='start' onclick='Start()'>Zaczynajmy</button>
<div class='textarea locked' contenteditable='true' data-text='Wpisz notkę...'></div>
<div class='btn__container locked'>
<button class='dodaj' onclick='add()'>Dodaj</button>
<button class='resetuj' onclick='reset()'>resetuj</button>
</div>
</div>
<div class='notes'></div>
</div>
I tried to make it this way, but it return an error (...'appendChild() is not a function...')
var del = document.createElement('div');
del.classList.add('del');
$('.notes').on('click', '.note', function(){
$(this).appendChild(del);
})
use already existing document to bind click on
$(document).on('click', '.note', function(){
$(this).appendChild(del);
})

CORS ERROR: Multiple CORS header ‘Access-Control-Allow-Origin’ not allowed

I am learning to use the "Article Search API" provided by the New York Times to allow my web application to display news articles based on the search results. I followed the tutorial at https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Third_party_APIs and used their javascript code as closely as I could. The issue is that when I clicked on the 'submit search' button, my web-developer's console on Firefox showed me the message:
"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://nyt-prod.apigee.net/svc/search/v2/articlesearch.json?api-key=(MY KEY: CENSORED)&page=0&q=Trump&fq=document_type:(%22article%22)&begin_date=2019-01-01&end_date=2019-01-05. (Reason: Multiple CORS header ‘Access-Control-Allow-Origin’ not allowed)."
This is where I am getting stuck. I really do not know what is happening here.
The 'Article Search API' is currently using the base URL 'https://nyt-prod.apigee.net/svc/search/v2/articlesearch.json', which I did carefully examine. I do not think the base-url has any problem, as can be conjectured based on the error message I got. I also tried to run this on Chrome and was using the Python testing server, but the problem remains.
I am willing to show the entire html file including the javascript.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>NY Times API example</title>
<link href="nytimes.css" rel="stylesheet">
</head>
<body>
<h1>NY Times video search</h1>
<div class="wrapper">
<div class="controls">
<form>
<p>
<label for="search">Enter a SINGLE search term (required): </label>
<input type="text" id="search" class="search" required>
</p>
<p>
<label for="start-date">Enter a start date (format YYYYMMDD): </label>
<input type="date" id="start-date" class="start-date" pattern="[0-9]{8}">
</p>
<p>
<label for="end-date">Enter an end date (format YYYYMMDD): </label>
<input type="date" id="end-date" class="end-date" pattern="[0-9]{8}">
</p>
<p>
<button class="submit">Submit search</button>
</p>
</form>
</div>
<div class="results">
<nav>
<button class="prev">Previous 10</button>
<button class="next">Next 10</button>
</nav>
<section>
</section>
</div>
</div>
<script>
// Defining a baseURL and key to as part of the request URL
var baseURL = 'https://nyt-prod.apigee.net/svc/search/v2/articlesearch.json';
var key = 'CENSORED';
var url;
// Grab references to all the DOM elements you'll need to manipulate
var searchTerm = document.querySelector('.search');
var startDate = document.querySelector('.start-date');
var endDate = document.querySelector('.end-date');
var searchForm = document.querySelector('form');
var submitBtn = document.querySelector('.submit');
var nextBtn = document.querySelector('.next');
var previousBtn = document.querySelector('.prev');
var section = document.querySelector('section');
var nav = document.querySelector('nav');
// Hide the "Previous"/"Next" navigation to begin with, as we don't need it immediately
nav.style.display = 'none';
// define the initial page number and status of the navigation being displayed
var pageNumber = 0;
var displayNav = false;
// Event listeners to control the functionality
searchForm.addEventListener('submit', submitSearch);
function submitSearch(e) {
pageNumber = 0;
fetchResults(e);
}
function fetchResults(e) {
// Use preventDefault() to stop the form from submitting:
e.preventDefault();
// Assemble the full URL:
url = baseURL + '?api-key=' + key + '&page=' + pageNumber + '&q=' + searchTerm.value + '&fq=document_type:("article")';
if (startDate.value !== '') {
url += '&begin_date=' + startDate.value;
}
if (endDate.value !== '') {
url += '&end_date=' + endDate.value;
}
// Use fetch() to make the request to the API
fetch(url).then(function(result) {
return result.json();
}).then(function(json) {
displayResults(json);
});
}
function displayResults(json) {
while (section.firstChild) {
section.removeChild(section.firstChild);
}
var articles = json.response.docs;
if(articles.length === 10) {
nav.style.display = 'block';
} else {
nav.style.display = 'none';
}
if(articles.length === 0) {
var para = document.createElement('p');
para.textContent = 'No results returned.'
section.appendChild(para);
} else {
for(var i = 0; i < articles.length; i++) {
var article = document.createElement('article');
var heading = document.createElement('h2');
var link = document.createElement('a');
var img = document.createElement('img');
var para1 = document.createElement('p');
var para2 = document.createElement('p');
var clearfix = document.createElement('div');
var current = articles[i];
console.log(current);
link.href = current.web_url;
link.textContent = current.headline.main;
para1.textContent = current.snippet;
para2.textContent = 'Keywords: ';
for(var j = 0; j < current.keywords.length; j++) {
var span = document.createElement('span');
span.textContent += current.keywords[j].value + ' ';
para2.appendChild(span);
}
if(current.multimedia.length > 0) {
img.src = 'http://www.nytimes.com/' + current.multimedia[0].url;
img.alt = current.headline.main;
}
clearfix.setAttribute('class','clearfix');
article.appendChild(heading);
heading.appendChild(link);
article.appendChild(img);
article.appendChild(para1);
article.appendChild(para2);
article.appendChild(clearfix);
section.appendChild(article);
}
}
};
</script>
</body>
</html>
But I think the most important lines are as follows:
var baseURL = 'https://nyt-prod.apigee.net/svc/search/v2/articlesearch.json';
var key = 'CENSORED';
...
...
url = baseURL + '?api-key=' + key + '&page=' + pageNumber + '&q=' + searchTerm.value + '&fq=document_type:("article")';
...
...
fetch(url).then(function(result) {
return result.json();
}).then(function(json) {
displayResults(json);
});
...
...
if(current.multimedia.length > 0) {
img.src = 'http://www.nytimes.com/' + current.multimedia[0].url;
img.alt = current.headline.main;
}
The news articles are supposed to show up on the right hand side in blocks arranged in a vertical fashion. With this error, I saw nothing. I hope someone can help me.

How to remove array objects from localStorage using dynamic buttons? [JS only]

New to JS here, been struggling with this one for a few hours now.
So I created a to do list with a button that stores objects in an array inside localStorage and also creates dynamic list items with content and delete buttons. Whenever I click the delete button it removes the dynamic list item but doesn't remove it from localStorage. I can't figure out how to assign each button to the specific array index in localStorage.
https://codepen.io/jupiterisland/pen/ooPXWV
var taskList = []; //build array
if(localStorage.taskList){ //call func to recreate li's on refresh
taskList = JSON.parse(localStorage.taskList) || [];
createTasks(taskList)
}
function submitFunc() {
var task = { //build objects
desc: document.getElementsByTagName("textarea")[0].value,
date: document.getElementsByTagName("input")[0].value,
time: document.getElementsByTagName("input")[1].value,
important: document.getElementsByTagName("input")[1].checked
};
if(task.desc && task.date !== ""){
taskList[taskList.length] = task; //put objects inside array
localStorage.taskList = JSON.stringify(taskList); //store array with stringify
newTaskList = JSON.parse(localStorage.taskList); //retrieve array with parse
createTasks(newTaskList)
document.getElementById("error").style.display = "none";
return false; //prevent submit
} else {
document.getElementById("error").style.display = "block";
document.getElementById("error").innerHTML = "Please enter a task description and a date.";
return false;
}
}
function createTasks (newTaskList){
for (i = 0; i < newTaskList.length; i++) { // display objects in list items
var currentTask = newTaskList[i];
var taskIndex = newTaskList.indexOf(currentTask);
newElement();
function newElement() {
var liNode = document.createElement("li");
var titleNode = document.createElement("h3");
var dNode = document.createElement("p");
var tNode = document.createElement("p");
var delNode = document.createElement("button")
liNode.className = "liNode";
titleNode.className = "titleNode";
dNode.className = "dNode";
tNode.className = "tNode";
delNode.className = "delete";
delNode.innerText = "Delete";
var titleText = newTaskList[i].desc;
var dateText = newTaskList[i].date;
var timeText = newTaskList[i].time;
var descNode = document.createTextNode(titleText);
var dateNode = document.createTextNode(dateText);
var timeNode = document.createTextNode(timeText);
titleNode.appendChild(descNode);
dNode.appendChild(dateNode);
tNode.appendChild(timeNode);
liNode.appendChild(titleNode);
liNode.appendChild(dNode);
liNode.appendChild(tNode);
liNode.appendChild(delNode);
document.getElementById("taskBoard").appendChild(liNode);
if (taskBoard.childElementCount > newTaskList.length) { //remove excess divs
for (n = 0; taskBoard.childElementCount - 2; n++) {
taskBoard.removeChild(taskBoard.firstChild);
}
}
function deleteTasks(){
var listItem = this.parentNode;
var ul = listItem.parentNode;
ul.removeChild(listItem);
}
delNode.addEventListener("click", deleteTasks);
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>My Task Board</h1>
<div class="container">
<form onsubmit="return submitFunc()">
<div>
<label for="">Task:</label>
<textarea name="name" rows="8" cols="80"placeholder="Please enter your task description"></textarea>
</div>
<div>
<label for="">Deadline:</label>
<input type="date" placeholder="Choose a date">
<input type="time" placeholder="Set time">
</div>
<div>
<label for="">Important:</label>
<input type="checkbox" name="" value="">
</div>
<button type="submit" name="button">Add Task</button>
<div id="error"></div>
</form>
</div>
<div>
<ul id="taskBoard"></ul>
</div>
</body>
</html>
var taskList = []; //build array
if(localStorage.taskList){ //call func to recreate li's on refresh
taskList = JSON.parse(localStorage.taskList) || [];
createTasks(taskList)
}
function fakeGuid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
function submitFunc() {
var task = { //build objects
desc: document.getElementsByTagName("textarea")[0].value,
date: document.getElementsByTagName("input")[0].value,
time: document.getElementsByTagName("input")[1].value,
important: document.getElementsByTagName("input")[1].checked,
id :fakeGuid()
};
if(task.desc && task.date !== ""){
taskList[taskList.length] = task; //put objects inside array
localStorage.taskList = JSON.stringify(taskList); //store array with stringify
newTaskList = JSON.parse(localStorage.taskList); //retrieve array with parse
createTasks(newTaskList)
document.getElementById("error").style.display = "none";
return false; //prevent submit
} else {
document.getElementById("error").style.display = "block";
document.getElementById("error").innerHTML = "Please enter a task description and a date.";
return false;
}
}
function createTasks (newTaskList){
for (i = 0; i < newTaskList.length; i++) { // display objects in list items
newElement(i);
function newElement(currentIndex) {
var liNode = document.createElement("li");
var titleNode = document.createElement("h3");
var dNode = document.createElement("p");
var tNode = document.createElement("p");
var delNode = document.createElement("button")
liNode.className = "liNode";
titleNode.className = "titleNode";
dNode.className = "dNode";
tNode.className = "tNode";
delNode.className = "delete";
delNode.innerText = "Delete";
var titleText = newTaskList[i].desc;
var dateText = newTaskList[i].date;
var timeText = newTaskList[i].time;
var descNode = document.createTextNode(titleText);
var dateNode = document.createTextNode(dateText);
var timeNode = document.createTextNode(timeText);
titleNode.appendChild(descNode);
dNode.appendChild(dateNode);
tNode.appendChild(timeNode);
liNode.appendChild(titleNode);
liNode.appendChild(dNode);
liNode.appendChild(tNode);
liNode.appendChild(delNode);
document.getElementById("taskBoard").appendChild(liNode);
if (taskBoard.childElementCount > newTaskList.length) { //remove excess divs
for (n = 0; taskBoard.childElementCount - 2; n++) {
taskBoard.removeChild(taskBoard.firstChild);
}
}
function deleteTasks(node, currentTask) {
var listItem = node.parentNode;
var ul = listItem.parentNode;
ul.removeChild(listItem);
taskList = taskList.filter(function(t) {
return t.id !== currentTask.id;
});
localStorage.taskList = JSON.stringify(taskList); //store array with stringify
}
var currentTask = newTaskList[currentIndex];
delNode.addEventListener("click", () => deleteTasks(delNode, currentTask));
}
}
}
Don't try to use index to manipulate DOM element. Instead use some kind of unique ID. In this case I created a fake GUID.
Read more on closure. The reason you are not able to pass index down to the function is because the index is bound to another context.
Any reason to stringify JSON for local storage? You can simply store an array.

Sort a list by Days of the week

I have created a list of items that contains information such as a taskname (i.e. take out the garbage), who must do the task, and what day of the week the task needs to be done by. All this information is gathered through text inputs in the html, then displayed as a list item using JavaScript.
Im wondering if there is a simple way to sort my list by the day of the week the task needs to be done. I was thinking perhaps i should add numerical value of 1-7 to strings containing days of the week. (for instance one that contains monday would have a value of 1, ones that have sunday have a value of 7). Then i could sort these numerically.
If anyone could show me how to do this with JavaScript (not jQuery), or an easier way, that would be greatly appreciated. (The more comments in the code the better).
Thanks
//links html elements to corresponding javascript variable names
var allTasks = document.getElementById('allTasks');
var taskInput = document.getElementById('taskInput');
var personInput = document.getElementById('personInput');
var dayInput = document.getElementById('dayInput');
var addBtn = document.getElementById('addBtn');
var sortBtn = document.getElementById('sortBtn');
//Create Task List based on input put in text fields
var TaskObject = function(taskText, personText, dayText){
var self = this;
self.name="taskName";
self.listItem;
self.init = function(){
//create html elements
self.listItem = document.createElement("li");
//create text box and have it display information from the previous inputed task
var text = document.createElement("text");
text.innerText = taskText + " ";
//create text box and have it display information from the previous inputed person
var text2 = document.createElement("text");
text2.innerText = personText + " ";
//create text box and have it display information from the previous inputed day of the week
var text3 = document.createElement("text");
text3.innerText = dayText + " ";
//create delete button and functionality
var deleteBtn = document.createElement("button");
deleteBtn.innerHTML = "delete";
deleteBtn.onclick = self.deleteMe;
// combine html elements
self.listItem.appendChild(text);
self.listItem.appendChild(text2);
self.listItem.appendChild(text3);
self.listItem.appendChild(deleteBtn);
allTasks.appendChild (self.listItem);
}
self.deleteMe = function(){
var parent = self.listItem.parentNode;
parent.removeChild(self.listItem);
}
}
addBtn.onclick = function (){
var newTask = new TaskObject(taskInput.value, personInput.value, dayInput.value)
newTask.init();
}
There is an in-built javascript function that helps in getting the day of the week.
//Calling the date function
var date = new Date();
//Getting the day of the week
var day_of_week = date.getDay();
date.getDay() returns a value from 0 to 6 for sunday to saturday respectively
//A function to get the day of the week
function dayOfTheWeek()
{
var date = new Date();
var day_of_week = date.getDay();
switch (day_of_week)
{
case 0: return "sunday"
case 1: return "monday"
case 2: return "tuesday"
case 3: return "wednessday"
case 4: return "thursday"
case 5: return "friday"
default: return "saturday"
}
}
//Calling the function
var day_of_week_in_string = dayOfTheWeek();
(javascript)
//define your task objects as an array (outside of TaskObject)
var tasks = [];
//retrieve a number rather than a text value
var dayInput = document.getElementById('dayInput').selectedIndex
var newTask = ...
//add this task object to the Task array
tasks.push(newTask)
//now you can sort the array:
tasks.sort(function(a, b){return a.dayInput-b.dayInput});
(html)
<select id="dayInput">
<option value="0">Monday</option>
<option value="1">Tuesday</option>
<option value="2">Wednesday</option>
<option value="3">Thursday</option>
<!-- etc.. -->
</select>
Here is my solution to your problem. When a new li is created, you store a hidden attribute called "data-day-text" and attach it to the li. When you sort, you remove the ul from the DOM (for performance gains), sort the lis according to the data-day-text, then re-attach the lis and the ul.
http://jsfiddle.net/g3et9abh/3/
html:
<div id="allTasksContainer">
<ul id="allTasks"></ul>
</div>
<p>task:
<input type="text" id="taskInput" />
</p>
<p>person:
<input type="text" id="personInput" />
</p>
<p>day:
<input type="text" id="dayInput" />
</p>
<button id="addBtn">add</button>
<button id="sortBtn">sort</button>
javascript:
//links html elements to corresponding javascript variable names
var allTasksContainer = document.getElementById('allTasksContainer');
var allTasks = document.getElementById('allTasks');
var taskInput = document.getElementById('taskInput');
var personInput = document.getElementById('personInput');
var dayInput = document.getElementById('dayInput');
var addBtn = document.getElementById('addBtn');
var sortBtn = document.getElementById('sortBtn');
//Create Task List based on input put in text fields
var TaskObject = function (taskText, personText, dayText) {
var self = this;
self.name = "taskName";
self.listItem;
self.init = function () {
//create html elements
self.listItem = document.createElement("li");
self.listItem.dataset.dayText = dayText;
//create text box and have it display information from the previous inputed task
var text = document.createElement("text");
text.innerText = taskText + ' ' + personText + ' ' + dayText;
//create delete button and functionality
var deleteBtn = document.createElement("button");
deleteBtn.innerHTML = "delete";
deleteBtn.onclick = self.deleteMe;
// combine html elements
self.listItem.appendChild(text);
self.listItem.appendChild(deleteBtn);
allTasks.appendChild(self.listItem);
}
self.deleteMe = function () {
var parent = self.listItem.parentNode;
parent.removeChild(self.listItem);
}
}
addBtn.onclick = function () {
var newTask = new TaskObject(taskInput.value, personInput.value, dayInput.value)
newTask.init();
}
sortBtn.onclick = function () {
allTasksContainer.removeChild(allTasks);
var nodes = [].slice.call(allTasks.getElementsByTagName('li'), 0);
[].sort.call(nodes, function (a, b) {
return b.dataset.dayText < a.dataset.dayText ? 1 : b.dataset.dayText > a.dataset.dayText ? -1 : 0;
});
while (allTasks.firstChild) {
allTasks.removeChild(allTasks.firstChild);
}
nodes.forEach(function (node) {
allTasks.appendChild(node);
});
allTasksContainer.appendChild(allTasks);
}

Categories