New to coding having issues with my JS code. It was working for a the last few days and then im not sure what happened now its giving me an error on line (17) todos.push(task); Error says "todos.push() is not a funsction." Any help would be greatly appreciated.
function get_todos()
{
var todos = new Array;
var todos_str = localStorage.getItem('todo');
if (todos_str !== null) {
todos = JSON.parse(todos_str);
}
return todos;
}
function add()
{
var task = document.getElementById('task').value;
var todos = get_todos();
todos.push(task);
localStorage.setItem('todo', JSON.stringify(todos));
show();
return false;
}
function remove()
{
var id = this.getAttribute('id');
var todos = get_todos();
todos.splice(id, 1);
localStorage.setItem('todo', JSON.stringify(todos));
show();
return false;
}
function show()
{
var todos = get_todos();
var html = '<table>';
for(var i=0; i<todos.length; i++)
{
html += '<br><tr><strong>'+
'<input type="image" src="/Pictures/remove.png" class="remove" id="' + i +
'"></input>' + todos[i] + '</strong><input type="checkbox" name="cBox" store="checkbox1" id="isDone"><label for="cBox"</label></tr><br>';
};
html += '</table>';
document.getElementById('todos').innerHTML = html;
var buttons = document.getElementsByClassName('remove');
for (var i=0; i < buttons.length; i++)
{
buttons[i].addEventListener('click', remove);
};
}
document.getElementById('add').addEventListener('click', add);
show();
My HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
</head>
<body>
<img id="mainImg" src="\Pictures\mytodolist.jpg"
<form>
<div>
<img id="taskImg" src="\Pictures\tasks.jpg"
<br>
<br>
<input id="add" type="image" width='150' heigth='80' src="\Pictures\addButton.png" ></input>
<br>
<input id="task">
</div>
<div id="todos"></div>
<script src= "ToDo.js"></script>
<link rel= "stylesheet" type= "text/css" href="todoStyle.css"/>
</body>
</html>
Seems to be working fine here: http://codepen.io/ilanus/pen/xOXJXW you declare an Array in your get_todos() function return it, then add items to it todos.push(task);
Related
I have been trying every method to update an array in my todo list using Javascript. But I am stuck in update function. I have tried every method possible but nothing seems to work.
Can anyone please help?
I have been stuck in the Update function for days now.I have declared the ind as a global variable. Assigned value in Edit functiion and called it back in update function. But still not working. Not sure, what the exact way is to update my array todo list in JS.
Below is my code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Arrays</title>
</head>
<script>
var arr = ["A", "B", "C"];
var ind;
function display() {
var dom = "<ul>";
for (i = 0; i < arr.length; i++) {
dom += "<li>" + arr[i] + "<input type='button' value='Edit' onclick='Edit(" + i + ")'></li>"
}
dom += "</ul>";
document.getElementById("do").innerHTML = dom;
}
function Selection(s) {
var ip = document.getElementById("input").value.trim();
var s;
switch (s) {
case 'op1':
arr.push(ip);
display();
break;
case 'op2':
arr.pop();
display();
break;
case 'op3':
arr.shift();
display();
break;
case 'op4':
arr.unshift(ip);
display();
break;
}
}
}
function Edit(ind) {
//alert(ind);
document.getElementById("editList").style.display = "Block";
document.getElementById("val").value = arr[ind];
ind = ind;
}
function update() {
Edit();
var updte = document.getElementById("val").value;
arr[ind] = updte;
}
</script>
<body onload="display()">
<h1>To Do List</h1>
<div id="do"></div>
Enter data : <input type="text" id="input"><br><br>
<input type="button" value="op1" onclick="Selection
('op1')">
<input type="button" value="op2" onclick="Selection('op2')">
<input type="button" value="op3" onclick="Selection('op3')">
<input type="button" value="op4" onclick="Selection('op4')">
<span id="select"></span>
<div id="editList" style="display:none">
<h2> Edit ToDo List</h2><br> To be updated: <input type="text" id="val"><br>
<input type="button" value="Update" onclick="update()">
</div>
</body>
</html>
Check at lines 46 and remove } symbol above edit function. You have 1 unnecessary symbol at this line
try to use let i in for (i = 0; i < arr.length; i++)
like this:
for (let i = 0; i < arr.length; i++) {
You need to have a way to know the actual ind when you click on the update button.
I have done it using dataset. Have a look at your edit and update functions below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Arrays</title>
<script>
var arr = ["A", "B", "C"];
var ind;
function display() {
var dom = "<ul>";
for (i = 0; i < arr.length; i++) {
dom += "<li>" + arr[i] + "<input type='button' value='Edit' onclick='Edit(" + i + ")'></li>"
}
dom += "</ul>";
document.getElementById("do").innerHTML = dom;
}
function Selection(s) {
var ip = document.getElementById("input").value.trim();
var s;
switch (s) {
case 'op1':
arr.push(ip);
display();
break;
case 'op2':
arr.pop();
display();
break;
case 'op3':
arr.shift();
display();
break;
case 'op4':
arr.unshift(ip);
display();
break;
}
}
function Edit(ind) {
//alert(ind);
document.getElementById("editList").style.display = "Block";
document.getElementById("val").value = arr[ind];
document.getElementById("val").dataset.ind = ind
ind = ind;
}
function update() {
//Edit();
var updte = document.getElementById("val").value;
ind = document.getElementById("val").dataset.ind
arr[ind] = updte;
display()
}
</script>
</head>
<body onload="display()">
<h1>To Do List</h1>
<div id="do"></div>
Enter data : <input type="text" id="input"><br><br>
<input type="button" value="op1" onclick="Selection
('op1')">
<input type="button" value="op2" onclick="Selection('op2')">
<input type="button" value="op3" onclick="Selection('op3')">
<input type="button" value="op4" onclick="Selection('op4')">
<span id="select"></span>
<div id="editList" style="display:none">
<h2> Edit ToDo List</h2><br> To be updated: <input type="text" id="val"><br>
<input type="button" value="Update" onclick="update()">
</div>
</body>
</html>
This is my html and my JavaScript is below
in my html this is what i did please help me solve this problem i have been struggling for a couple of days not and i really don't know what i am doing wrong
this is my html and my JavaScript is below
let artistV = [];
function myPage() {
// body...
let htmlSelect = document.getElementById("artistList");
htmlSelect.style.visibility = "hidden";
if (sessionStorage.getItem("hasCodeRunBefore") === null) {
let arrayArt = [];
sessionStorage.setItem("artists", JSON.stringify(artistV));
sessionStorage.setItem("hasCodeRunBefore", true);
} else {
artistV = JSON.parse(sessionStorage.getItem("artists"));
let i = 0;
artistV.forEach(function(art) {
let listItems = document.createElements("li");
listItems.innerHTML = art.name.artist;
listItems.value = i;
i = i + 1;
htmlSelect.appendChild(listItems);
});
if (i > 0) {
htmlSelect.style.visibility = "visible";
}
}
}
function Artist(name, title, genre, album) {
// body...
this.name = name;
this.title = title;
this.genre = genre;
this.album = album;
}
function submit() {
// body...
artistV = JSON.parse(sessionStorage.getItem("artists"));
let newArtist = new Artist(
document.getElementById("name").value,
document.getElementById("title").value,
document.getElementById("genre").value,
document.getElementById("album").value
);
artistV.push(newArtist);
sessionStorage.setItem("artists", JSON.stringify(artistV));
}
function userInput(artistInfo) {
// body...
artistV[artistInfo].bio = function() {
document.getElementById("artistList").innerHTML = "<li value=''>"
this.name + 'Title is' + this.title + 'Genre is' + this.genre + 'Album is'
this.album + "</li>";
};
artistV[artistInfo].bio();
}
<!DOCTYPE html>
<html>
<head>
<title>Music</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script type="text/javascript" src="music.js"></script>
</head>
<body onload="myPage()">
<h1>Artist information</h1>
<br>
<form>
<label for="artistName">Artist name</label><input type="text" id="name" required>
<label>Title</label><input type="text" id="title" required>
<label>Genre</label><input type="text" id="genre" required>
<label>Album</label><input type="text" id="album" required>
<button id="btn" onclick="submit()">Submit</button>
</form>
<ul id="artistList" onchange="userInput(this.value)">
<li value=""></li>
</ul>
</body>
</html>
this is my JavaScript and i am not quite sure why it is not working to save what the user inputs on
[help], [help/on-topic]
Try renaming submit() function in your script to something else(say submitData).
Submit() method is inbuilt method which is used to submit the form to server.
This is my html here i am taking elements from user and trying to update in js.
This my script file
// Initializing the Stack Class
function Stack() {
this.dataStore = [];
this.top = 0;
this.push = push; // Inserting the element in Stack
this.pop = pop; //Removing the element in Stack
this.peek = peek;
this.clear = clear;
this.length = length;
}
// Adding an element in Stack
function push(element) {
this.dataStore[this.top++] = element;
}
function peek() {
return this.dataStore[this.top - 1];
}
// Removing an element from the given stack
function pop() {
return this.dataStore[-this.top];
}
function clear() {
this.top = 0;
}
function length() {
return this.top;
}
var s = new Stack();
function pushToStack(el){
s.push(el);
}
<!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> <!-- <div> <input type="text" id="stackName"> <button onclick="MakeStack()">Make a stack</button> </div> -->
<div>
<input type="text" id="elemet">
<button onclick="pushToStack(document.getElementById('elemet').value)">
Push an elemet
</button>
</div>
<div class="container"></div>
<script src="script.js"></script>
</body>
</html>
What i want is that when i click on push button the data from text filed should save in array as stack and data should show in container as my element of Stack. Thanks for help.
append the input to the Container, here is the code. Hope this is what you are looking for.
// Initializing the Stack Class
function Stack() {
this.dataStore = [];
this.top = 0;
this.push = push; // Inserting the element in Stack
this.pop = pop; //Removing the element in Stack
this.peek = peek;
this.clear = clear;
this.length = length;
}
// Adding an element in Stack
function push(element) {
this.dataStore[this.top++] = element;
}
function peek() {
return this.dataStore[this.top - 1];
}
// Removing an element from the given stack
function pop() {
return this.dataStore[-this.top];
}
function clear() {
this.top = 0;
}
function length() {
return this.top;
}
var s = new Stack();
function pushContainer(el){
//console.log(el);
var x = document.getElementById("container");
x.appendChild(el);
}
function pushToStack(el){
//
var newElement = document.createElement("p");
var Textnode = document.createTextNode(el);
newElement.appendChild(Textnode);
pushContainer(newElement);
s.push(el);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<div>
<input type="text" id="elemet">
<button onclick="pushToStack(document.getElementById('elemet').value)">Push an elemet</button>
</div>
<div id="container">
</div>
</body>
</html>
You can modify your push function as :
function pushToStack(el){
s.push(el);
var para = document.createElement("p");
var node = document.createTextNode(el);
para.appendChild(node);
document.querySelector('.container').appendChild(para);
}
for working code, please refer:this pen
Modify your push function then:
function push(element) {
this.dataStore[this.top++] = element;
var div = document.createElement('div');
div.textContent = element;
document.getElementById('container').appendChild(div);
}
I'm trying to pick a value from JSON and insert it on a diferents text boxes but it show the value "undefined". The objective is insert link on name space and link space and save it on LocalStorage and some statick values like google and yahoo. Please can someone help me? Thanks you so much.
EDIT: Now is solved, and now dont work the buttons, some one? Please
NEW PROBLEM:The error only appear if I press the buttons (it don't create the buttons).
ERROR: Can't find variable SSL
html:
<!DOCTYPE html>
<html>
<head>
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/script.js"></script>
<script type="text/javascript" src="js/json.json" charset="utf-8"></script>
</head>
<body onLoad="start()">
<div id="title">
<h1>SSL Checker</h1>
</div>
<div id="data">
<form action="javascript:void(0);" method="POST" onsubmit="SSL.Add()">
<input type="text" id="add-name" placeholder="Name"></input>
<input type="text" id="add-link" placeholder="Link"></input>
<input type="submit" value="Add">
</form>
<div id="edit" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
</div>
<div id="table">
<table style="overflow-x:auto;">
<tr>
<th>Sites:</th>
</tr>
<tbody id="urls">
</tbody>
</table>
</div>
</body>
</html>
js:
function start() {
var SSL = new function() {
//List urls to check
this.el = document.getElementById('urls');
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'url';
if (data) {
if (data > 1) {
name = 'urls';
}
el.innerHTML = 'There are:' + ' ' + data + ' ' + name;
} else {
el.innerHTML = 'No ' + name;
}
};
//Buttons configuration
this.FetchAll = ss =function() {
var data= '';
if (MyJSON.length > 0) {
for (i = 0; i < MyJSON.length; i++) {
data += '<tr>';
data += '<td>' + MyJSON[i].name+ '</td>';
data += '<td><button onclick="SSL.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="SSL.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(MyJSON.length);
return this.el.innerHTML = data;
};
//Add name
this.Add = function() {
el = document.getElementById('add-name');
el1 = document.getElementById('add-link')
var url = el.value;
var url1 = el1.value;
if (url) {
MyJSON.name.push(url.trim());
el.value = '';
this.FetchAll();
}
if (url) {
MyJSON.url.push(url1.trim());
el1.value = '';
this.FetchAll();
}
}
//Edit
this.Edit = function(item) {
var el = document.getElementById('edit-name');
el.value = MyJSON.name[item];
document.getElementById('edit').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
var url = el.value;
if (url) {
self.urls.splice(item, 1, url.trim());
self.FetchAll();
CloseInput();
}
}
};
//Delete
this.Delete = function(item) {
MyJSON.name.splice(item, 1);
this.FetchAll();
};
}
SSL.FetchAll();
function CloseInput() {
document.getElementById('edit').style.display = 'none';
}
}
How can I make my event listener work on inserted HTML?
I insert
<li id="test">Titre : test<input type="button" id="del" value="X"><br>Texte : </li>
on my list, but my event listener only works on the button named "work", which is created in the HTML page.
I want to call the function clickHandlerRem by clicking on the new button in the list.
Image:
Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<link href="libs/css1.css" rel="stylesheet">
<script src="/script1.js"></script>
</head>
<body>
<form>
Ajouter une note
<input type="text" id="oTitleInput" placeholder="Entrez un titre" />
<input type="button" id="bdel" value="Supprimer"/>
<input type="text" id="oTextInput" placeholder="Entrez une note ici" />
<input type="button" id="binput" value="Ajouter"/>
<div class="divlist">
<ul class="notelist" id="notelist">
</ul>
</div>
</form>
<input type="button" id="del" value="work"/>
</body>
</html>
And my JavaScript code:
function clickHandler(e) {
addnote();
}
function clickHandlerDel(e) {
var oTitle = document.getElementById("oTitleInput").value;
delnote(oTitle);
document.getElementById("oTitleInput").value = '';
document.getElementById("oTextInput").value = '';
}
function clickHandlerRem(e) {
var oTitle = "test";
delnote(oTitle);
}
function addnote() {
var oTitle = document.getElementById("oTitleInput").value;
document.getElementById("oTitleInput").value = '';
var oText = document.getElementById("oTextInput").value;
document.getElementById("oTextInput").value = '';
localStorage.setItem(oTitle, oText);
affnote();
}
function affnote() {
var node = document.getElementById("notelist");
while (node.firstChild) {
node.removeChild(node.firstChild);
}
for (var i = 0, len = localStorage.length; i < len; i++) {
var key = localStorage.key(i);
var value = localStorage[key];
var html = "<li id=\"" + key + "\">Titre : " + key + "\<input type=\"button\" id=\"del\" value=\"X\"\/\><br />Texte : " + value + "</li>";
document.querySelector('#notelist').innerHTML += html;
}
}
function delnote(keyname) {
localStorage.removeItem(keyname);
affnote();
}
function main() {
affnote();
}
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('#binput').addEventListener('click', clickHandler);
document.querySelector('#bdel').addEventListener('click', clickHandlerDel);
document.querySelector('#del').addEventListener('click', clickHandlerRem);
main();
});
Javascript will not reattach event handlers after you create a new DOM element. You will have to add the event handler to your new element manually:
Run
document.querySelector('#del').addEventListener('click', clickHandlerRem);
at the end of affnote().