Edit function for to do list - javascript

I am working on a homework to do list application based in HTML and Javascript. I am currently trying to implement an edit function but cannot figure out how to call a div tag within a child element. The edit function needs to be able to copy the contents displayed in the tag into the text area.
Here is my code:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<meta charset="utf-8">
<title>Homework</title>
</head>
<body>
<h1>Homework Tracker</h1>
<br>
<div class="AddNewSub"> <i class="material-icons" style="font-size:30px; vertical-align: middle;">receipt</i>
<textarea id="addhw" placeholder="Input Homework"></textarea>
<button type="button" id="addbutton" onclick="add()"> Add </button>
</div>
<br>
<div id="MainContents"> </div>
<script>
document.getElementById("MainContents").innerHTML = JSON.parse(localStorage.getItem('UserInputCon'));
function add() {
var contents = document.getElementById('addhw').value;
contents = contents.replace(/\r?\n/g, '<br />');
var newline = document.createElement('div');
newline.setAttribute("class", "close");
newline.setAttribute("id", "UserConDiv")
newline.innerHTML = "<div id='contentdiv'>" + contents + "</div>" + " " + "<button type='button' id='delbutton' onclick='deletehw(this)'>Delete</button>" + "<button type='button' id='delbutton' onclick='edithw(this)'>Edit</button>" + "<br>";
document.getElementById("MainContents").appendChild(newline);
localStorage.setItem('UserInputCon', JSON.stringify(document.getElementById("MainContents").innerHTML));
}
function deletehw(element) {
let container = element.parentElement;
container.parentNode.removeChild(container);
localStorage.removeItem('UserInputCon');
localStorage.setItem('UserInputCon', JSON.stringify(document.getElementById("MainContents").innerHTML));
}
function edithw(element) {
var conDiv = document.getElementById('contentdiv').innerHTML;
var i;
for (i = 0; i < conDiv.length; i++) {
document.getElementById('addhw').value = conDiv[i].innerHTML;
var container = element.parentElement;
container.parentNode.removeChild(container);
localStorage.removeItem('UserInputCon');
localStorage.setItem('UserInputCon', JSON.stringify(document.getElementById("MainContents").innerHTML));
}
}
</script>
</body>
</html>

This is what you edithw function could be:
function edithw(element)
{
let text = element.parentElement.getElementsByTagName('div')[0].innerHTML
document.getElementById('addhw').value = text;
}
What you are missing in your edithw function is needing to get the innerHtml from a div that was within the generated parent div.
You don't need to worry about looping over anything, since you already have the parent element of the data you want.
element.parentElement gets your the parent div, but you cannot call getElementById from a parentElement, instead use getElementsByTagName, then get the innerHtml of whatever child you want, in this case it was the first element.
You can console.log() it out as you go to see what you get from each call to make it easier to understand:
function edithw(element)
{
console.log('element',element);
console.log('element.parentElement',element.parentElement);
console.log('element.parentElement.getElementsByTagName',element.parentElement.getElementsByTagName('div'));
let text = element.parentElement.getElementsByTagName('div')[0].innerHTML
document.getElementById('addhw').value = text;
}
Here is the full code:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<meta charset="utf-8">
<title>Homework</title>
</head>
<body>
<h1>Homework Tracker</h1>
<br>
<div class="AddNewSub"> <i class="material-icons" style="font-size:30px; vertical-align: middle;">receipt</i>
<textarea id="addhw" placeholder="Input Homework"></textarea>
<button type="button" id="addbutton" onclick="add()"> Add </button>
</div>
<br>
<div id="MainContents"> </div>
<script>
document.getElementById("MainContents").innerHTML = JSON.parse(localStorage.getItem('UserInputCon'));
function add() {
var contents = document.getElementById('addhw').value;
contents = contents.replace(/\r?\n/g, '<br />');
var newline = document.createElement('div');
newline.setAttribute("class", "close");
newline.setAttribute("id", "UserConDiv")
newline.innerHTML =
"<div id='contentdiv'>" +
contents +
"</div>" +
" " +
"<button type='button' id='delbutton' onclick='deletehw(this)'>Delete</button>" +
"<button type='button' id='editbutton' onclick='edithw(this)'>Edit</button>" +
"<br>";
document.getElementById("MainContents").appendChild(newline);
localStorage.setItem('UserInputCon', JSON.stringify(document.getElementById("MainContents").innerHTML));
}
function deletehw(element) {
let container = element.parentElement;
container.parentNode.removeChild(container);
localStorage.removeItem('UserInputCon');
localStorage.setItem('UserInputCon', JSON.stringify(document.getElementById("MainContents").innerHTML));
}
function edithw(element)
{
console.log('element',element);
console.log('element.parentElement',element.parentElement);
console.log('element.parentElement.getElementsByTagName',element.parentElement.getElementsByTagName('div'));
let text = element.parentElement.getElementsByTagName('div')[0].innerHTML
document.getElementById('addhw').value = text;
}
</script>
</body>
</html>

Related

Javascript and HTML Homework tracker. Delete function not working correctly

I have been working on a homework tracker. I am currently able to add and delete homework items which are inputted by the user. However, there is a problem where if you delete an item by clicking the delete button, you can click anywhere on any other homework item and it will delete it even though you did not press the delete button.
Here is my code:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<meta charset="utf-8">
<title>Homework</title>
</head>
<body>
<h1>Homework Tracker</h1>
<br>
<div class="AddNewSub">
<i class="material-icons" style="font-size:30px; vertical-align: middle;">receipt</i>
<textarea id="addhw" placeholder="Input Homework"></textarea>
<button type="button" id="addbutton" onclick="add()"> Add </button>
</div>
<br>
<div id="MainContents">
</div>
<script>
var close = document.getElementsByClassName("close");
document.getElementById("MainContents").innerHTML = JSON.parse(localStorage.getItem('UserInputCon'));
function add() {
var contents = document.getElementById('addhw').value;
contents = contents.replace(/\r?\n/g, '<br />');
var newline = document.createElement('div');
newline.setAttribute("class", "close");
newline.setAttribute("id", "UserConDiv")
newline.innerHTML = "<div id='contentdiv'>" + contents + "</div>" + " " + "<button type='button' id='delbutton' onclick='deletehw()'>Delete</button>" + "<br>";
document.getElementById("MainContents").appendChild(newline);
localStorage.setItem('UserInputCon', JSON.stringify(document.getElementById("MainContents").innerHTML));
}
function deletehw() {
var i;
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
this.parentNode.removeChild(this);
localStorage.removeItem('UserInputCon');
localStorage.setItem('UserInputCon', JSON.stringify(document.getElementById("MainContents").innerHTML));
}
}
}
</script>
</body>
</html>
You have to change your delete function. At the moment you are iteration over the "close" items, but close is not the button but the whole homework entry, so on click on any of this, you will delete them.
Try this code:
But i would suggest you to use event binding and not directly print onclick in the element. Also you should use a template for your homework entry
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<meta charset="utf-8">
<title>Homework</title>
</head>
<body>
<h1>Homework Tracker</h1>
<br>
<div class="AddNewSub">
<i class="material-icons" style="font-size:30px; vertical-align: middle;">receipt</i>
<textarea id="addhw" placeholder="Input Homework"></textarea>
<button type="button" id="addbutton" onclick="add()"> Add </button>
</div>
<br>
<div id="MainContents">
</div>
<script>
var close = document.getElementsByClassName("close");
document.getElementById("MainContents").innerHTML = JSON.parse(localStorage.getItem('UserInputCon'));
function add() {
var contents = document.getElementById('addhw').value;
contents = contents.replace(/\r?\n/g, '<br />');
var newline = document.createElement('div');
newline.setAttribute("class", "close");
newline.setAttribute("id", "UserConDiv")
newline.innerHTML = "<div id='contentdiv'>" + contents + "</div>" + " " + "<button type='button' id='delbutton' onclick='deletehw(this)'>Delete</button>" + "<br>";
document.getElementById("MainContents").appendChild(newline);
localStorage.setItem('UserInputCon', JSON.stringify(document.getElementById("MainContents").innerHTML));
}
function deletehw(element) {
let container = element.parentElement;
container.parentNode.removeChild(container);
localStorage.removeItem('UserInputCon');
localStorage.setItem('UserInputCon', JSON.stringify(document.getElementById("MainContents").innerHTML));
}
</script>
</body>
</html>

How do I remove a to do list item after it is added

I really tried everything, almost every function in JS. But I cannot remove the list item from the to-do list once it is added. I have tried adding event listeners, onclick=" " etc but nothing works. Can someone please look at my code and tell me what I am doing wrong. Thank You, any help is much appreciated.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<script src="script.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet href="style.css">
<link rel="stylesheet" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<meta charset="UTF-8">
<title>To-Do-List</title>
</head>
<body>
<div class="container">
<div id="header">
<h1>My To Do List</h1>
</div>
<form autocomplete="off">
<input type="text" id="task" placeholder="Title...">
</form>
<button id="addTask">Add</button>
</div>
<br><br>
<div id="tasks">
<ul id="myUL">
</ul>
</div>
</div>
</div>
<script>
var list = document.getElementById('myUL');
list.addEventListener("click", boxChecked);
function boxChecked(event){
const element = event.target;
if(element.type === "close"){
delete element;
}
}
</script>
</body>
</html>
JS:
$(document).ready(function(){
document.getElementById('addTask').addEventListener("click", function(){
var task = document.getElementById('task').value;
if(task == ""){
alert("You Must Enter A Value!");
}else{
document.getElementById('myUL').innerHTML += '<li>' + task + '</li>' + '<button class="close" >&#10007</button>' + '<br><br>' + '<button class="check" >✓</button>' + '<br><br>';
}
var button = document.querySelectorAll('.close');
for(var i = 0; i < button.length;i++){
button[i].addEventListener("click", function(){
this.parentNode.removeChild(this.previousSibling);
this.parentNode.removeChild(this);
});
}
var check = document.querySelectorAll('.check');
for(var i = 0; i < check.length;i++){
check[i].addEventListener("click", function(){
this.parentNode.style.textDecoration = "line-through";
});
}
});
});
Don't try to concatenate innerHTML strings when you have listeners attached to elements inside, else the listeners will be lost. Instead, append elements properly with appendChild.
delete element won't actually do anything, because element is a variable, not a property of an object - try using .remove() instead, to remove the li (and put the button inside the li so that the HTML is valid).
var list = document.getElementById('myUL');
list.addEventListener("click", boxChecked);
function boxChecked(event) {
const element = event.target;
if (element.className === "close") {
element.parentElement.remove();
}
}
document.getElementById('addTask').addEventListener("click", function() {
var task = document.getElementById('task').value;
if (task === "") return alert("You Must Enter A Value!");
const li = list.appendChild(document.createElement('li'));
li.textContent = task;
const button = li.appendChild(document.createElement('button'));
button.className = 'close';
button.textContent = '✗';
});
.close {
position: absolute;
left: 150px;
}
<div class="container">
<div id="header">
<h1>My To Do List</h1>
</div>
<form autocomplete="off">
<input type="text" id="task" placeholder="Title...">
</form>
<button id="addTask">Add</button>
</div>
<br><br>
<div id="tasks">
<ul id="myUL">
</ul>
</div>
Your .querySelectorAll() simply needs to target .close rather than close. In addition to this, you'll probably want to target the close button's parent (the item itself), with .parentNode. Note that you probably don't want to hide it, but rather actually simply remove both the <li> and the close icon, so that you can add more items after removal of the item(s). This can be done with:
this.parentNode.removeChild(this.previousSibling);
this.parentNode.removeChild(this);
And can be seen working in the following:
var list = document.getElementById('myUL');
list.addEventListener("click", boxChecked);
function boxChecked(event) {
const element = event.target;
if (element.type === "close") {
delete element;
}
}
$(document).ready(function() {
document.getElementById('addTask').addEventListener("click", function() {
var task = document.getElementById('task').value;
if (task == "") {
alert("You Must Enter A Value!");
} else {
document.getElementById('myUL').innerHTML += '<li>' + task + '</li>' + '<button class="close" >&#10007</button>' + '<br><br>';
}
var button = document.querySelectorAll('.close');
for (var i = 0; i < button.length; i++) {
button[i].addEventListener("click", function() {
this.parentNode.removeChild(this.previousSibling);
this.parentNode.removeChild(this);
});
}
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script src="script.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<meta charset="UTF-8">
<title>To-Do-List</title>
</head>
<body>
<div class="container">
<div id="header">
<h1>My To Do List</h1>
</div>
<form autocomplete="off">
<input type="text" id="task" placeholder="Title...">
</form>
<button id="addTask">Add</button>
</div>
<br><br>
<div id="tasks">
<ul id="myUL">
</ul>
</div>
</body>
</html>
Also note that your stylesheet is missing a closing ", and you have two additional closing </div> that don't match anything in your above code.

How to show html tags from javascript variable to a div id?

I want to show the testTag variable to the div after i click the button. When i clicked it only shows the label of the option tag and not the full select tags.
Please help! This is my code.
function showDropdown() {
var textTag = "<select>";
var textOptions = ["option1","option2","option3"];
for (i = 0; i < textOptions.length; i++) {
textTag += '<options value="' + textOptions[i] + '">' + textOptions[i] + "</options>";
}
textTag += "</select>";
document.getElementById("dropdownTest").innerHTML= textTag;
console.log(textTag);
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Show dropdown</title>
</head>
<body>
<input type="button" id="showDrop" value="Show dropdown" onClick="showDropdown()">
<div id="dropdownTest"></div>
</body>
</html>
It's called <option>, not <options>:
function showDropdown() {
var textTag = "<select>";
var textOptions = ["option1","option2","option3"];
// declare "i"!
for (var i = 0; i < textOptions.length; i++) {
// change this line
textTag += '<option value="' + textOptions[i] + '">' + textOptions[i] + "</option>";
}
textTag += "</select>";
document.getElementById("dropdownTest").innerHTML = textTag;
console.log(textTag);
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Show dropdown</title>
</head>
<body>
<input type="button" id="showDrop" value="Show dropdown" onClick="showDropdown()">
<div id="dropdownTest"></div>
</body>
</html>

How to create a dynamic search page

I am new to javacript. I used an API for implementing custom search feature. But in my search page results show only after I enter the first search key. If I enter another search key, the results for the second key don't show up until I refresh the page.
How can I get the results to auto-update when entering more characters into the search box?
HTML code:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<link href="../css/style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="../js/jsonData.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function display() {
document.location = "contentpage.html";
}
$(document).ready(function () {
$("#submit").click(searchAPI);
});
</script>
</head>
<body>
<input type="text" id="search1" >
<button id="submit" >submit</button>
<div id="div1">
<img id="img" >
<p id="desc"> </p>
<p></p>
</div>
</body>
</html>
My JS Code:
function searchAPI(){
var key= $("#search1").val();
var htmlContent="<ul>";
$.getJSON('http://api.duckduckgo.com/?q=' + key + ' &format=json&pretty=1&callback=?', function(data) {
var htmlContent = '<ul>';
for (var i = 0; i < data.RelatedTopics.length; i++) {
var desc = data.RelatedTopics[i].Text;
var url = data.RelatedTopics[i].Icon.URL;
var link = data.RelatedTopics[i].FirstURL;
document.getElementById('link').href = link;
var y = document.getElementById("link");
y.innerHTML = link;
htmlContent += "<li><img src='" + url + "' style='width:100px;height:100px;display:block'/> " +
"<p id='desc'>" + desc + "</p>" + "<a target='_blank' id='link' href=" + link + " >go to website</a></li>";
}
htmlContent += "</ul>";
$('#div1').html(htmlContent);
});
}
Can anyone help me to solve this issue...Thanks in advance.

Clear the output area

I have here a working code that lets the user input something and it displays the output right away, but I want to create a function triggered by a button that would clear the output area itself. Is this possible with my code?
Here is my complete code:
<html>
<meta charset="UTF-8">
<head>
<title>Sample Array</title>
<script>var index = 0;</script>
</head>
<body>
Input:
<input type="text" id="input">
<input type="button" value="GO" onClick="press(input.value)">
<p id = "display">
<script>
var sample = new Array();
function press(Number)
{
if ( Number != '' )
{
sample[index] = Number;
document.getElementById("display").innerHTML += sample[index] + "<br>";
index++;
}
else
alert("empty");
document.getElementById('input').value = '';
}
</script>
</body>
</html>
Try this,
Javascript:
function Clean(){
document.getElementById('display').innerHTML='';
}
HTML:
<input type="button" value="Clean" onClick="Clean()"/>
Do this:
Notes:
-I have closed the P element.
-A new button was added "Clean" and you can use JQuery as it is shown below to clean the output (remember to have JQuery referenced in your page).
<html>
<meta charset="UTF-8">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<title>Sample Array</title>
<script>var index = 0;</script>
</head>
<body>
Input:
<input type="text" id="input" />
<input type="button" value="GO" onClick="press(input.value)"/>
<input type="button" value="Clean" onClick="$('#display').html('');"/>
<p id = "display"></p>
<script>
var sample = new Array();
function press(Number)
{
if ( Number != '' )
{
sample[index] = Number;
document.getElementById("display").innerHTML += sample[index] + "<br>";
index++;
}
else
alert("empty");
document.getElementById('input').value = '';
}
</script>
</body>

Categories

Resources