JavaScript - Dynamic To-do list - Editing list - javascript

For this To-do list, I am able to add a list. However, once added, I am having issue editing the list that already been added. What I am hoping is when you click Edit, you should able to edit the information and upload the edited information (and making sure the edited information is saved in the local storage when you click Save List to Local Storage). Can someone please help me and go over the JavaScript code and see what I am doing wrong? Below is the HTML, JavaScript and CSS codes:
Here is the Dropbox link if it is easier to download the files: https://www.dropbox.com/sh/qaxygbe95xk4jm1/AADPO98m4416d-ysSGjNt12La?dl=0
<html>
<head>
<title>Dynamic To-do List</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="Dynamic To-do List.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript"></script>
<script src="Dynamic To-do List.js" defer="defer"></script>
</head>
<body onload="loadList();">
<h1>To-Do List</h1> Click Button to Add List: Add List
<div id="listFormDiv">
<form id="addListForm">
List name :
<input type="text" id="listNameTxt"><br />
Description : <textarea name="description" id="listDescTxt"></textarea><br />
Date: <input type="text" id="listDateTxt"><br />
Urgent (Yes or No) :
<select id="listUrgentTxt" name="Urgent">
<option value="Yes"> Yes </option>
<option value="No"> No </option>
</select><br />
Category :
<select id="listCategoryTxt" name="category">
<option value="School"> School </option>
<option value="Work"> Work </option>
<option value="Home"> Home </option>
<option value="Others"> Others </option>
</select>
<input type="button" id="addListBtn" value="Add List" onclick="addList()" />
<input type="button" id="updateListBtn" value="Update List" onclick="updateList()" style="visibility: hidden" />
</form>
</div>
<div id="container">
Save List to Local Storage<br />
Clear Local Storage<br />
<div id="listsDiv">
Add To-Do list here<br />
Hide List<br />
Show List<br />
</div>
</div>
</body>
</html>
sortableList();
$(function() {
$("#listDateTxt").datepicker();
});
function loadList() {
console.log(localStorage.getItem("lists"));
var taskList = JSON.parse(localStorage.getItem("lists"));
if (!taskList) {
console.log("There are no tasks saved in the local storage");
} else {
for (var i = 0; i < taskList.length; i++) {
createListDiv(taskList[i]);
}
}
}
//get a reference to the listFormDiv div tag that has the add To-Do List form. list is a global variable that can be access easily from any function
var listFormDiv = getElement("listFormDiv");
var listArray = Array(); //list will hold all the To-do list added through the form
var listIDCount = 0; // list variable will be incremented every time a list is added and will be used to assing a unique ID to every list object.
if (localStorage.getItem("lists")) {
listArray = JSON.parse(localStorage.getItem("lists"));
}
function clearStorage() {
localStorage.clear();
listArray = [];
}
function getElement(id) {
return document.getElementById(id);
}
//function to show the div with the add to-do list form when the add list hyperlink is clicked onLine
function showListDiv() {
//var st = window.getComputedStyle(listFormDiv,null);
console.log(listFormDiv);
listFormDiv.style.display = "block";
}
//list function adds a list when the "add list" button on the form is pressed - 3rd step
function addList() {
var listName = getElement("listNameTxt").value;
var listDesc = getElement("listDescTxt").value;
var listDate = getElement("listDateTxt").value;
var listUrgent = getElement("listUrgentTxt").value;
var listCategory = getElement("listCategoryTxt").value;
//create an instance of the list object with the values from the form
var f;
if (listCategory == "School") {
f = new schoolTask();
f.setValues(listName, listDesc, listDate, listUrgent, listCategory, "blue");
} else if (listCategory == "Work") {
f = new workTask();
f.setValues(listName, listDesc, listDate, listUrgent, listCategory, "red");
}
console.log("school task is " + JSON.stringify(f));
//clear the textboxes in the form
getElement("listNameTxt").value = "";
getElement("listDescTxt").value = "";
getElement("listDateTxt").value = "";
getElement("listUrgentTxt").value = "";
getElement("listCategoryTxt").value = "";
var listAddButton = getElement("addListBtn");
var listEditButton = getElement("updateListBtn");
console.log(listAddButton);
//listAddButton.style.visibility = "visible";
listEditButton.style.visibility = "hidden";
listFormDiv.style.display = "none";
//add the new list object to the global listArray.
listArray.push(f);
//increment the listID count
listIDCount++;
//add the list to the page and pass in the newly created list object to the createListDiv function
createListDiv(f)
}
// a list object - the second step
function setValues(name, desc, date, urgent, category, color) {
this.name = name;
this.desc = desc;
this.date = date;
this.urgent = urgent;
this.category = category;
this.color = color;
}
function list() {}
//list.prototype.name = "blank name";
list.prototype.name = "blank";
list.prototype.desc = "blank desc";
list.prototype.date = "blank";
list.prototype.urgent = "blank";
list.prototype.category = "blank";
list.prototype.listID = "blank";
list.prototype.color = "blank";
list.prototype.setValues = setValues;
//list.prototype.name = "test";
function schoolTask() {
this.address = "25 Timau Road";
}
inheritFrom(schoolTask, list);
function workTask() {
this.room = "303f";
}
inheritFrom(workTask, list);
function inheritFrom(child, parent) {
child.prototype = Object.create(parent.prototype);
}
//create a div tag to represent the new list and add the new div to the existing place holder div on the page
function createListDiv(list) {
var listDiv = document.createElement("DIV");
listDiv.setAttribute("class", "listClass");
var nameTxt = document.createElement("DIV");
nameTxt.innerHTML = "To-do List Name: " + list.name;
nameTxt.id = "nameTxt" + list.listID;
var lineBreak = document.createElement("BR");
var descTxt = document.createElement("DIV");
descTxt.innerHTML = "Description: " + list.desc;
descTxt.id = "descTxt" + list.listID;
var dateTxt = document.createElement("DIV");
dateTxt.innerHTML = "Date: " + list.date;
dateTxt.id = "dateTxt" + list.listID;
var urgentTxt = document.createElement("DIV");
urgentTxt.innerHTML = "Urgent: " + list.urgent;
urgentTxt.id = "urgentTxt" + list.listID;
var categoryTxt = document.createElement("DIV");
categoryTxt.innerHTML = "Category: " + list.category;
categoryTxt.id = "categoryTxt" + list.listID;
var editLink = document.createElement("A");
editLink.setAttribute("onclick", "editList(" + list.listID + ");"); //Note that we are passing the listID from the list object when calling the editList so we know which list object to fetch to edit when we are editing
editLink.setAttribute("href", "#");
editLink.id = "editLink" + list.listID;
editLink.innerHTML = "Edit";
listDiv.appendChild(nameTxt);
listDiv.appendChild(lineBreak);
listDiv.appendChild(descTxt);
listDiv.appendChild(lineBreak);
listDiv.appendChild(dateTxt);
listDiv.appendChild(lineBreak);
listDiv.appendChild(urgentTxt);
listDiv.appendChild(lineBreak);
listDiv.appendChild(categoryTxt);
listDiv.appendChild(lineBreak);
listDiv.appendChild(editLink);
getElement("listsDiv").appendChild(listDiv);
}
//global variable to remember which element in the listArray we are editing
var listIndex;
function editList(listID) {
//get the the list object from the array based on the index passed in
var list;
//show the update list button on the html form and hide the add list button on the same form
var listAddButton = getElement("addListBtn");
var listEditButton = getElement("updateListBtn");
listAddButton.style.visibility = "hidden";
listEditButton.style.visibility = "visible";
//iterate through the listsArray until we find the list object that has the same ID as the id passed in to the function
for (var i = 0; i < listArray.length; i++) {
//if the listID in the list object is the same as the listID passed in to the function then assign the object from the array to the list variable in list function
if (listArray[i].listID == listID) {
//we found the list with the right ID
list = listArray[i];
listIndex = i;
}
}
listFormDiv.style.display = "block";
getElement("listNameTxt").value = list.name;
getElement("listDescTxt").value = list.desc;
getElement("listDateTxt").value = list.date;
getElement("listUrgentTxt").value = list.urgent;
getElement("listCategoryTxt").value = list.category;
//updateList(listIndex);
}
//list function will be called when the update button is pressed on the form
function updateList() {
//save the changed information from the form into the list object in the array based on the array index passed in
listArray[listIndex].name = getElement("listNameTxt").value;
listArray[listIndex].desc = getElement("listDescTxt").value;
listArray[listIndex].date = getElement("listDateTxt").value;
listArray[listIndex].urgent = getElement("listUrgentTxt").value;
listArray[listIndex].category = getElement("listCategoryTxt").value;
var listID = listArray[listIndex].listID; // get the listID from the list object that is in the listsArray at the specificed index;
//now reflect the same changes in the DIV that shows the list
getElement("nameTxt" + listID).innerHTML = "To-do List Name: " + getElement("listNameTxt").value;
getElement("descTxt" + listID).innerHTML = "Description: " + getElement("listDescTxt").value;
getElement("dateTxt" + listID).innerHTML = "Date: " + getElement("listDateTxt").value;
getElement("urgentTxt" + listID).innerHTML = "Urgent: " + getElement("listUrgentTxt").value;
getElement("categoryTxt" + listID).innerHTML = "Category: " + getElement("listCategoryTxt").value;
//reset the listIndex to a value that does not exisit in the array index
listIndex = -1;
var listAddButton = getElement("addListBtn");
var listEditButton = getElement("updateListBtn");
listAddButton.style.visibility = "visible";
listEditButton.style.visibility = "hidden";
//reset form div visibility
listFormDiv.style.display = "none";
getElement("listNameTxt").value = "";
getElement("listDescTxt").value = "";
getElement("listDateTxt").value = "";
getElement("listUrgentTxt").value = "";
getElement("listCategoryTxt").value = "";
}
//Sortable list - http://jqueryui.com/sortable/
function sortableList() {
$("#listsDiv").sortable({
update: function(updateList) {
var sortOrder = getElement(list).sortable('listArray').toString();
console.log(sortOrder);
}
});
}
function saveLists() {
localStorage.setItem("lists", JSON.stringify(listArray));
}
//Hide and Show list
function hideList() {
var listsDiv = getElement("listsDiv");
if (listsDiv.style.display == "block") {
//listsDiv.style.display = "none";
alert("Find a way to hide the list");
}
}
function showList() {
var listsDiv = getElement("listsDiv");
if (listsDiv.style.display == "none") {
listsDiv.style.display = "block";
}
}
#listFormDiv {
border: 1px solid black;
height: 350px;
width: 200px;
position: absolute;
top: 100px;
left: 100px;
padding: 10px;
display: none;
}
#listsDiv { /*Possible #listsDiv*/
height: 350px;
width: 200px;
}
#listDescTxt {
height: 100px;
}
#container {
border: 1px solid black;
height: 650px;
width: 400px;
margin-bottom: 20px;
position: absolute;
top: 100px;
left: 500px;
}
.listClass {
border: 1px solid red;
height: 160px;
width: 200px;
padding: 5px;
}

list.listID is assigned "Blank";
coming from this >
//list.prototype.name = "blank name";
list.prototype.name = "blank";
list.prototype.desc = "blank desc";
list.prototype.date = "blank";
list.prototype.urgent = "blank";
list.prototype.category = "blank";
Line 145: list.prototype.listID = "blank";
list.prototype.color = "blank";
list.prototype.setValues = setValues;
That is why
when it is assigned here >
Line 204: editLink.setAttribute("onclick","editList(" + list.listID + ");");
You click the edit button, it is sending not an *ID but a "blank".
You probably want to reassign the id here >
Line 110: //Assign the id before you push eg. (f.listID == listIDCount++)
//add the new list object to the global listArray.
listArray.push(f);
//increment the listID count
//listIDCount++; why am I incrementing?
//add the list to the page and pass in the newly created list object to the createListDiv function
createListDiv(f)

Related

Display slider when you hover over array elements and give value to the array elements

I have done the part where you have to generate the array elements when you enter them from textbox, what I struggle with now is to display a slider on hover over each array element and give the array element a value, also what I struggle with is to delete each generated array element individually, my delete function deletes the entire array on click not just the single element I click.
Here is how it should look like:
enter image description here
Here is my code so far:
let names = [];
let nameInput = document.getElementById("name");
let messageBox = document.getElementById("display");
function insert ( ) {
names.push( nameInput.value );
clearAndShow();
}
function remove()
{
var element = document.getElementById("display");
element.parentNode.removeChild(element);
}
function clearAndShow () {
let printd=""
nameInput.value = "";
messageBox.innerHTML = "";
names.forEach(function(element){
if(element != ''){
var _span = document.createElement('span');
_span.style.borderStyle = "solid"
_span.style.borderColor = "blue"
_span.style.width = '50px'
_span.style.marginLeft = "5px"
_span.appendChild(document.createTextNode(element))
messageBox.appendChild(_span)
printd +="''" + element + "''" + "," + " ";
document.getElementById("labelprint").innerHTML=(printd)
}
})
}
h3 {
color: rgb(0, 174, 255);
}
.container {
border: solid 2px;
display: block;
margin-left: 200px;
margin-right: 200px;
margin-top: 50px;
}
<div class="container">
<form>
<h1>Enter Search</h1>
<input id="name" type="text" />
<input type="button" value="Search" onclick="insert()" />
</form>
<br/>
<div onclick="remove(this)" id="display"></div>
<br/>
<label >You have Selected: </label>
<h3 id="labelprint"></h3>
</div>
I am not being rude I just got confused on how you stated your message but what I think you are saying is to do this:
var names = [];
var nameInput = document.getElementById("name");
var messageBox = document.getElementById("display");
function insert ( ) {
names.push( nameInput.value );
// add value to array val: names[names.length - 1] = PutValueHere
clearAndShow();
}
function remove(this){
document.getElementById("display").parentNode.firstChild.remove(); // If you want it to remove the last child with the id 'display' then do .parentNode.lastChild.remove()
//if you are trying to remove the last val in the array do this: names.splice(names.length-1,1) for the first do this names.splice(0,1)
}
function clearAndShow () {
var printd=""
nameInput.value = "";
messageBox.innerHTML = "";
names.forEach(function(element){
if(element != ''){
var _span = document.createElement('span');
_span.id = '_spanId'
$('_spanId').css('border-style',solid');
$('_spanId').css('border-color',blue');
$('_spanId').css('width',50+'px');
$('_spanId').css('margin-left',5+'px');
_span[0].appendChild(document.createTextNode(element))
messageBox[0].appendChild(_span)
printd += "''" + element + "'', ";
document.getElementById("labelprint").innerHTML = printd
}
})
}
I have tried to implement something that i hope it's close to what are you looking for:
HTML:
<div class="container">
<form>
<h1>Add new slider</h1>
<input id="sliderName" type="text" />
<input type="button" value="Add" onclick="insertSlider()" />
</form>
<div id="display"></div>
</div>
CSS:
h3 {
color: rgb(0, 174, 255);
}
.container {
border: solid 2px;
display: block;
margin-left: 200px;
margin-right: 200px;
margin-top: 50px;
}
JS:
let messageBox = document.getElementById("display");
function deleteFn(id) {
const element = document.getElementById(id)
if(element) element.outerHTML="";
}
function onChangeSlideId(id){
const elementSlide = document.getElementById('slider-'+id+'')
if(elementSlide){
const value = elementSlide.value
const elementSlideText = document.getElementById('slider-value-'+id+'')
elementSlideText.innerText = '('+value+')'
}
}
function insertSlider(){
const name = document.getElementById("sliderName")
const nameValue = name.value
const newLabel = document.createElement('label')
newLabel.setAttribute('for',nameValue)
newLabel.innerText = nameValue
const newSlider = document.createElement('input')
newSlider.setAttribute('id','slider-'+nameValue+'')
newSlider.setAttribute('type','range')
newSlider.setAttribute('name',nameValue)
newSlider.setAttribute('onchange','onChangeSlideId("'+nameValue+'")')
const sliderValue = document.createElement('span')
sliderValue.setAttribute('id','slider-value-'+nameValue+'')
sliderValue.innerText = '('+newSlider.value+')'
const newContainer = document.createElement('div')
newContainer.setAttribute('id',nameValue)
newContainer.setAttribute('style','display: grid')
newContainer.appendChild(newSlider)
newContainer.appendChild(newLabel)
newContainer.appendChild(sliderValue)
const newDeleteButton = document.createElement('input')
newDeleteButton.setAttribute('type', 'button')
newDeleteButton.setAttribute('value', 'Delete ' + nameValue + '')
newDeleteButton.setAttribute('onclick', 'deleteFn("'+nameValue+'")')
newContainer.appendChild(newDeleteButton)
messageBox.appendChild(newContainer)
}
You can try it by yourself in this codepen

Want to remove previously appended table

When I Click on submit button after clicking on the links it appends perfectly but when I hit the button again it doesn't remove previously appended table.
I want to clear the previously created table when user clicks on the cross button and then print the table again or else overwrite the table but instead it is not removing the table and prints a new one.Image Part OneImage Part TwoImage Part ThreeImage Part Four
//variables
var order1 = document.getElementById('one').innerText;
var order2 = document.getElementById('two').innerText;
var order3 = document.getElementById('three').innerText;
var order4 = document.getElementById('four').innerText;
var temp = 0;
var orders_list = []; //Array
//Object Orientation To Create Order And Then Add It In Array
function orders(name) {
this.name = name;
if (orders_list[temp] == null) {
orders_list.push(name);
}
temp++;
}
//Main Function Which Creates Orders
function order_maker(order_name) {
var order = new orders("." + order_name);
}
//To Append Child Each Time Submit Buton Is Pressed And Check the Loop
function loop(argument) {
var i = 0;
while (i < orders_list.length) {
var temporary = document.createElement("table");
var orders_temp_list = orders_list[i];
temporary.innerHTML = "<tr><td>" + orders_list[i] + "</td><td onclick='remove(" + i + ")'>×</td></tr>";
document.body.appendChild(temporary);
//This Block Is That I was Checking
if (argument == "f") {
temporary.innerHTML = " ";
}
if (argument == "t") {
console.log("Done");
}
i++;
}
}
//To Remove The Specific Element User Want To Delete
function remove(id) {
orders_list.splice(id, id);
loop("t");
}
a {
margin: 20px;
padding: 30px;
}
table {
border: 3px solid #242424;
}
tr,
td {
padding: 20px;
}
<!DOCTYPE html>
<head></head>
<body>
Cake1
Cake2
Cake3
Cake4
<form>
<input placeholder="name">
<input placeholder="email">
<input placeholder="order">
</form>
<p id="para"></p>
<button onclick="loop('t')">Click</button>
</body>
Update your remove function as function remove(el) { el.closest('table').remove(); }.
Update parameter in html as "</td><td onclick='remove(this)'>×</td></tr>".
And add orders_list = []; in the end of loop function.
Try it below.
//variables
var order1 = document.getElementById('one').innerText;
var order2 = document.getElementById('two').innerText;
var order3 = document.getElementById('three').innerText;
var order4 = document.getElementById('four').innerText;
var temp = 0;
var orders_list = []; //Array
//Object Orientation To Create Order And Then Add It In Array
function orders(name) {
this.name = name;
if (orders_list[temp] == null) {
orders_list.push(name);
}
temp++;
}
//Main Function Which Creates Orders
function order_maker(order_name) {
var order = new orders("." + order_name);
}
//To Append Child Each Time Submit Buton Is Pressed And Check the Loop
function loop(argument) {
var i = 0;
while (i < orders_list.length) {
var temporary = document.createElement("table");
var orders_temp_list = orders_list[i];
temporary.innerHTML = "<tr><td>" + orders_list[i] + "</td><td onclick='remove(this)'>×</td></tr>";
document.body.appendChild(temporary);
//This Block Is That I was Checking
if (argument == "f") {
temporary.innerHTML = " ";
}
if (argument == "t") {
console.log("Done");
}
i++;
}
orders_list = [];
}
//To Remove The Specific Element User Want To Delete
function remove(el) {
el.closest('table').remove();
}
a {
margin: 20px;
padding: 30px;
}
table {
border: 3px solid #242424;
}
tr,
td {
padding: 20px;
}
<!DOCTYPE html>
<head></head>
<body>
Cake1
Cake2
Cake3
Cake4
<form>
<input placeholder="name">
<input placeholder="email">
<input placeholder="order">
</form>
<p id="para"></p>
<button onclick="loop('t')">Click</button>
</body>

JavaScript arrays adding last element instead of recently added input

Good evening. I am new to JavaScript and I need help with my mini-project and I have only one issue here and it is in the this.Add = function ().
It works properly when I enter a duplicate value from my list therefore it displays an alert that no dupes are allowed. But... when I enter a unique value, it only adds up the last element present (Wash the dishes) from myTasks list. instead of the one I recently entered and the list goes on adding the same ones. Did I just misplace something?
This is my final activity yet and I want to finish it to move to the next function. Thank you in advance.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tasks CRUD</title>
<style>
#tasks{
display: none;
}
</style>
</head>
<body>
<center>
<form action="javascript:void(0);" method="POST" onsubmit="app.Add()">
<input type="text" id="add-task" placeholder="Add another card">
<input type="submit" value="Add">
</form>
<div id="tasks" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-task">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
<table>
<tr>
<th>Name</th>
</tr>
<tbody id="myTasks">
</tbody>
</table>
</center>
<script>
var app = new function() {
this.el = document.getElementById('myTasks');
this.myTasks = ['Clean the bathroom', 'Wash the dishes'];
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'task';
if (data) {
if (data > 1) {
name = 'Things To DO';
}
el.innerHTML = data + ' ' + name ;
} else {
el.innerHTML = 'No ' + name;
}
};
this.FetchAll = function() {
var data = '';
if (this.myTasks.length > 0) {
for (i = 0; i < this.myTasks.length; i++) {
data += '<tr>';
data += '<td>' + this.myTasks[i] + '</td>';
data += '<td><button onclick="app.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="app.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(this.myTasks.length);
return this.el.innerHTML = data;
};
this.Add = function () {
el = document.getElementById('add-task');
// Get the value
var task = el.value;
if (task ) {
for(task of this.myTasks)
{
var ctr = 0;
if(document.getElementById("add-task").value == task){
ctr = 1;
break;
}
}
if(ctr == 1)
{
window.alert("Duplicates not allowed.");
}else{
// Add the new value
this.myTasks.push(task.trim());
// Reset input value
el.value = '';
// Dislay the new list
this.FetchAll();
}
}
};
this.Edit = function (item) {
var el = document.getElementById('edit-task');
// Display value in the field
el.value = this.myTasks[item];
// Display fields
document.getElementById('tasks').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
// Get value
var task = el.value;
if (task) {
// Edit value
self.myTasks.splice(item, 1, task.trim());
// Display the new list
self.FetchAll();
// Hide fields
CloseInput();
}
}
};
this.Delete = function (item) {
// Delete the current row
this.myTasks.splice(item, 1);
// Display the new list
this.FetchAll();
};
}
app.FetchAll();
function CloseInput() {
document.getElementById('tasks').style.display = 'none';
}
</script>
</body>
</html>
In your for loop:
for (task of this.myTask) {
}
You are not declaring a new task variable, but instead assigning to the outer task variable, hence the repeated addition of tasks already in your list.
You can declare a new variable in the for scope like so:
for (const task of this.myTask) {
}
Your HTML as it is.
And your Javascript goes like below. You have a bug while checking if the task already exists in the array. As you're comparing string value either use simple for loop with triple equals or do as i have attached below.
var app = new function() {
this.el = document.getElementById('myTasks');
this.myTasks = ['Clean the bathroom', 'Wash the dishes'];
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'task';
if (data) {
if (data > 1) {
name = 'Things To DO';
}
el.innerHTML = data + ' ' + name ;
} else {
el.innerHTML = 'No ' + name;
}
};
this.FetchAll = function() {
var data = '';
if (this.myTasks.length > 0) {
for (i = 0; i < this.myTasks.length; i++) {
data += '<tr>';
data += '<td>' + this.myTasks[i] + '</td>';
data += '<td><button onclick="app.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="app.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(this.myTasks.length);
console.log(this.myTasks.length);
return this.el.innerHTML = data;
};
this.Add = function () {
el = document.getElementById('add-task');
// Get the value
var task = el.value;
console.log(task);
if (task ){
var arrayContainsTask = (this.myTasks.indexOf(task) > -1);
if(arrayContainsTask == true){
window.alert("Duplicates not allowed.");
}else{
// Add the new value
this.myTasks.push(task);
// Reset input value
el.value = '';
}
// Dislay the new list
this.FetchAll();
}
}
}

Having trouble with displaying an image through an array

I am practicing with JavaScript Array function. What I want to achieve is to show google embedded images inside the display section when the user clicks "Show my grocery list" button after entering "banana", else the texts will be shown instead.
These are my codes.
var grocery = document.getElementById("grocery");
let showItems = document.getElementById("showItems");
const display = document.getElementById("display");
var groceryList = [];
grocery.addEventListener("keyup",function(ev){
if(ev.keyCode == 13){
groceryList.push(grocery.value);
console.log("array",groceryList);
}
});
showItems.addEventListener("click",function(){
for (var i = 0; i < groceryList.length;i++){
if(groceryList[i] == "banana"){
display.src = "https://i5.walmartimages.ca/images/Enlarge/271/747/6000191271747.jpg";
} else {
display.innerHTML += groceryList[i] + "<br/>";
}
}
});
#display {
width:100px;
height:100px;
}
<div id="controls">
<input type="text" placeholder="grocery items" id="grocery"/>
<button id="showItems">Show My Grocery List</button>
</div>
<div id="display"></div>
It is currently not showing anything. I have a feeling that I have written a wrong syntax inside the loop function? I would appreciate a solution and tips. Thank you.
You've to remove the keyCode=13 condition first and then need to create an img element with src of image based on condition (groceryList[i] == "banana") to display the image inside the <div> element, For example:
var grocery = document.getElementById("grocery");
let showItems = document.getElementById("showItems");
const display = document.getElementById("display");
var groceryList = [];
grocery.addEventListener("keyup", function(ev) {
//if(ev.keyCode == 13){
groceryList.push(grocery.value);
//console.log("array",groceryList);
//}
});
showItems.addEventListener("click", function() {
for (var i = 0; i < groceryList.length; i++) {
if (groceryList[i] == "banana") {
var source = "https://i5.walmartimages.ca/images/Enlarge/271/747/6000191271747.jpg";
var img = document.createElement("IMG"); //create img element
img.src = source; //set img src
display.appendChild(img); // display image inside <div>
} else {
display.innerHTML += groceryList[i] + "<br/>";
}
}
});
<div id="controls">
<input type="text" placeholder="grocery items" id="grocery" />
<button id="showItems">Show My Grocery List</button>
</div>
<div id="display"></div>

How to create a <ul> based on an array number

I am trying to make a GitHub profile searcher and what i'm trying to do is:
Get the user Avatar
Get the user Name
Get the user Repositories
I'm having troubles with the last one.
What i can't figure out is how to create a UL based in the user repos quantity.
What i have HTML:
<!DOCTYPE html>
<html>
<head>
<title>Github Profile Searcher</title>
<link rel="stylesheet" href="github-profile.css" />
</head>
<body>
<div id="username-input" class="username-input">
Username:
<input class="username-input-text" type="text" />
</div>
<div id="github-profile" class="github-profile">
<div class="github-profile-avatar">
<span class="github-profile-username">mmckalan</span>
</div>
<div class="github-profile-name">
Alan Mac Cormack
</div>
<div class="github-profile-location">
Napoli,NA
</div>
<div class="github-profile-stats">
<div class="github-profile-stat">
<i class="icon github-icon-repo" /></i>
<span id = "github-profile-repo-count" class="github-profile-repo-count">50</span>
</div>
<div class="github-profile-stat">
<i class="icon github-icon-gist" /></i>
<span class="github-profile-gist-count">12</span>
</div>
</div>
</div>
<script src="github-profile.js"></script>
</body>
JS:
var usernameInput = document.querySelector('#username-input .username-input-text');
var emptyUser = {
login: "",
name: "",
location: "",
public_repos: "",
public_gists: "",
avatar_url: "notfound.png"
};
usernameInput.addEventListener('change', function(event){
var ghReq = new XMLHttpRequest();
ghReq.addEventListener("load", updateProfileBadge);
ghReq.open("GET", "https://api.github.com/users/" + usernameInput.value);
ghReq.send();
});
function updateProfileBadge() {
var response = JSON.parse(this.reponseText);
if (response.message === "Not Found") {
updateDomWithUser(emptyUser);
} else {
updateDomWithUser(response);
}
}
function updateDomWithUser(user) {
var profile = document.getElementById('github-profile');
profile.querySelector('.github-profile-username').innerText = user.login;
profile.querySelector('.github-profile-name').innerText = user.name;
profile.querySelector('.github-profile-location').innerText = user.location;
profile.querySelector('.github-profile-repo-count').innerText =
user.public_repos;
profile.querySelector('.github-profile-gist-count').innerText =
user.public_gists;
profile.querySelector('.github-profile-avatar')
.style.backgroundImage = "url(" + user.avatar_url + ")";
}
updateDomWithUser(emptyUser);
var quantity = document.getElementById('github-profile-repo-count');
var ul = document.createElement("ul");
document.body.appendChild(ul);
What i'm trying to do is something like this:
The quantity of LI is based on the number given by user.public_repos
But it has to fit to the user repos quantity, so i don't know how to solve it.
Could u please give me a hand?
As far as I know, call to "https://api.github.com/users/NAME" would give you only the number of public respos, not names or stars. For that, you need to call "https://api.github.com/users/NAME/repos" - it may be chained after the first call.
Still, creating X list elements without data is quite easy:
var ul = document.createElement("ul");
document.body.appendChild(ul);
for (var i = 0; i < user.public_repos; i++) {
var li = document.createElement("li");
li.textContent = 'example text';
ul.appendChild(li)
}
Or, if you'll get the repos data itself, in form of array:
var ul = document.createElement("ul");
document.body.appendChild(ul);
repos.forEach((repo)=>{
var li = document.createElement("li");
li.textContent = repo.name;
ul.appendChild(li)
})
Another thing - it's better to write
public_repos: 0,
than empty string.
To create a list of repos, you just have to loop through the JSON data returned by /users/{my_user}/repos. In your case, you need two Ajax calls:
The first one gives you information about the user
The second one gives you information about the user repos
Here is a minimal working example with my repositories:
function get(endpoint, callback) {
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (this.readyState === XMLHttpRequest.DONE) {
if (this.status === 200) {
var data = JSON.parse(this.responseText);
callback(data);
} else {
console.log(this.status, this.statusText);
}
}
};
req.open('GET', 'https://api.github.com' + endpoint, true);
req.send(null);
}
function handleUser(data) {
var html = '';
html += '<li>' + data.login + '</li>';
html += '<li>' + data.name + '</li>';
document.querySelector('#user > ul').innerHTML = html;
get('/users/Badacadabra/repos', handleUserRepos);
}
function handleUserRepos(data) {
var html = '';
for (var i = 0; i < data.length; i++) {
html += '<li>' + data[i].name + '</li>';
}
document.querySelector('#repos > ul').innerHTML = html;
}
get('/users/Badacadabra', handleUser);
<div id="user">
<ul></ul>
</div>
<hr>
<div id="repos">
<ul></ul>
</div>

Categories

Resources