So I have this expense tracker website, it's just a beginner JavaScript project. I have an issue with deleting rows. If I click on the delete button it always deletes the first row below the heading, rather than deleting the row which I want to delete.
HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="styles.css" />
<script
src="https://kit.fontawesome.com/60cb322ae0.js"
crossorigin="anonymous"
></script>
<title>Expense Tracker</title>
</head>
<body>
<div class="wrapper">
<h1>Expense Tracker</h1>
<form action="">
<label for="">Name</label>
<input
class="name"
type="text"
placeholder="Where was the expense made"
/><br />
<label for="">Date</label>
<input class="date" type="date" />
<label for="">Amount</label>
<input class="amount" type="number" /><br />
<button class="btn" type="submit">Add Expense</button>
</form>
</div>
<table>
<tr>
<th>Name</th>
<th>Date</th>
<th>Amount</th>
<th></th>
</tr>
</table>
<script src="index.js"></script>
</body>
</html>
JavaScript Code
const name = document.querySelector(".name");
const date = document.querySelector(".date");
const amount = document.querySelector(".amount");
const btton = document.querySelector(".btn");
const table = document.querySelector("table");
//Event
btton.addEventListener("click", toTable);
table.addEventListener("click", toDelete);
//fucntion
function toTable(event) {
event.preventDefault();
//creating table row
const tableRow = table.insertRow();
//creating table definitions
const tableName = tableRow.insertCell();
const tableDate = tableRow.insertCell();
const tableAmount = tableRow.insertCell();
const tableDelete = tableRow.insertCell();
tableDelete.classList.add("trash");
//assigning values
tableName.innerHTML = name.value;
tableDate.innerHTML = date.value;
tableAmount.innerHTML = amount.value;
tableDelete.innerHTML = "<i class='far fa-trash-alt'></i>";
//making the input fields clear
name.value = "";
date.value = "";
amount.value = "";
}
function toDelete(event) {
var item = document.querySelector(".trash");
item = item.parentElement;
item.remove();
}
Sorry for this mess of a code, I just started coding.
When you do document.querySelector(".trash") it will fetch the first element on the page with a trash class. That is why the first row gets deleted.
What you should probably do is search for the parentElements class from the event you are getting.
Something like this:
function toDelete(event) {
let row=event.target.closest(".parents-class");
row.remove();
}
event.target will give you a reference to the object on which the event was dispatched. In your case this is probably the element that was clicked. From there we try to move up the DOM to the parent that we want to delete and then remove it.
Alternatively you could search for the closest tr tag and directly delete it that way:
function toDelete(event) {
let row=event.target.closest("tr");
row.remove();
}
Related
I'm new to JS and I'm just practicing. I have this form that sets data in an object which is later displayed on the DOM. It works but it just shows a "key" at a time. If I add new elements they replace the existing one.
class Items {
constructor(namee, surnamee) {
this.namee = namee;
this.surnamee = surnamee;
}
}
function Func() {
event.preventDefault();
var nameval = document.getElementById('namee').value;
var surnval = document.getElementById('surnamee').value;
let newIt = new Items(nameval, surnval);
console.log(newIt)
document.getElementById('box').innerHTML = newIt.namee + " " + newIt.surnamee
}
<form onsubmit={Func()}>
<input id="namee" > </input>
<input id="surnamee"> </input>
<button type=submit> send </button>
</form>
<p id="box"> </p>
I've tried the push() method but it works with arrays. I've also tried to create an object instead of a class but I get the same grief
Thank you in advance
Maybe you looking for this:
class Items {
constructor(namee, surnamee) {
this.namee = namee;
this.surnamee = surnamee;
}
}
function Func() {
event.preventDefault();
var nameval = document.getElementById('namee').value;
var surnval = document.getElementById('surnamee').value;
let newIt = new Items(nameval, surnval);
console.log(newIt)
document.getElementById('box').innerHTML += `<p>` + newIt.namee + " " + newIt.surnamee + `</p>`;
}
<form onsubmit={Func()}>
<input id="namee" > </input>
<input id="surnamee"> </input>
<button type=submit> send </button>
</form>
<p id="box"> </p>
class Items {
constructor(namee, surnamee) {
this.namee = namee;
this.surnamee = surnamee;
}
}
function Func() {
event.preventDefault();
var nameval = document.getElementById('namee').value;
var surnval = document.getElementById('surnamee').value;
let newIt = new Items(nameval, surnval);
let html = `${document.getElementById('box').innerHTML}<p>${newIt.namee} ${newIt.surnamee}</p>`
document.getElementById('box').innerHTML = html
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title></title>
</head>
<body>
<form onsubmit={Func()}>
<input id="namee" > </input>
<input id="surnamee"> </input>
<button type=submit> send </button>
</form>
<p id="box"> </p>
</body>
</html>
Hope it help :)
or you can use this
https://www.w3schools.com/jsref/met_node_appendchild.asp
any stored value can be wrapped in a div tag
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title></title>
</head>
<body>
<form onsubmit={Func()}>
<input id="namee" > </input>
<input id="surnamee"> </input>
<button type=submit> send </button>
</form>
<p id="box"> </p>
</body>
</html>
<script>
class Items {
constructor(namee, surnamee) {
this.namee = namee;
this.surnamee = surnamee;
}
}
function Func() {
event.preventDefault();
var nameval = document.getElementById('namee').value;
var surnval = document.getElementById('surnamee').value;
let newIt = new Items(nameval, surnval);
console.log(newIt)
const row = document.createElement('div');
row.innerText = newIt.namee + " " + newIt.surnamee;
document.getElementById('box').appendChild(row);
}
</script>
every time I refresh my page my data input that displays in the table disappears but it saves in my real-time database in firebase i expect my data will remain on table even I close the page
I just want data in the table wont disappear every time I refresh HTML/page
this is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Data input</title>
<meta charset="utf-8">
<link href="style01.css" rel="stylesheet" type="text/css" />
</head>
<body>
Username:
<input type="text" name="User" id="Username" /><br />
Password:
<input type="text" name="Pass" id="Password" /><br />
Email:
<input type="text" name="email" id="Email" /><br /><br />
<input type="button" value="Add" onClick="addRow()" id="add"><br /><br />
<table id="table" border="1">
<tr>
<th>Username</th>
<th>Password</th>
<th>Email</th>
</tr>
</table>
</body>
</html>
<script src="https://www.gstatic.com/firebasejs/8.4.0/firebase.js"></script>
<script src="firebase003.js"></script>
this is my javascript the first part is where my data that I input save in my database to firebase
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Retrieve the database handle (handle is a type of function)
const myDBCxn = firebase.database().ref('/User_Yahoo');
//Information is the name of the root node in the project data tree.
const btn = document.getElementById("add");
btn.addEventListener("click", saveData);
// Submit clicked so post the data to the server
function saveData() {
// Read the data from the first name field
const UserField = document.getElementById("Username");
const UserFieldValue = UserField.value;
// Read the data from the age field
const passwordField = document.getElementById("Password");
const passwordFieldValue = passwordField.value;
// Read the data from the Email field
const EmailField = document.getElementById("Email");
const EmailFieldValue = EmailField.value;
// code to save the data to Firebase GOES HERE!
const data = myDBCxn.push();
data.set( {Username: UserFieldValue,password: passwordFieldValue,Email: EmailFieldValue });
}
function addRow() {
"use strict";
var table = document.getElementById("table");
var row= document.createElement("tr");
console.log(row);
var td1 = document.createElement("td");
var td2 = document.createElement("td");
var td3 = document.createElement("td");
td1.innerHTML = document.getElementById("Username").value;
td2.innerHTML = document.getElementById("Password").value;
td3.innerHTML = document.getElementById("Email").value;
row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);
table.children[0].appendChild(row);
};
I'm making a code where the user enters information and it stores it in an object, but when I check if the object is saved by alerting one of its values it says there is no such object.
here is my code.
let users = {};
function user(name,real){
this.username = name,
this.realname = real,
this.id = Math.floor(Math.random() *1000);
this.subs = 0,
this.videos = [],
this.listuser = function() {
return this.username;
}
};
function newuser(name, email,username){
users[name] = new user(username, name);
};
let savefile = () => {
var channame = string(document.getElementById('channame'));
var name = string(document.getElementById('name'));
var email = string(document.getElementById('email'));
newuser(name,email,channame);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>youtube ripoff</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<br> <br><br><br><br><br>
<form action="">
<label for="username">Channel Name: </label>
<input type="text" id="channame" name="channelname"><br>
Real Name
<input type="text" id="name" name="name"><br>
Email
<input type="text" id="email" name="email"><br>
<input type="submit" value="Submit" onmousedown="newuser('name1','name#gmail.com','channelname1');">
<br><br><br><br>
<input type="button" value="Load Channels" id="seech" name="seechannels" onmousedown="alert(users['name1'].listuser());"><br>
</form>
<script src="script.js">
function fun(){
window.alert("starting program...")
//other code
}
</script>
</body>
</html>
Is there some sort of error that I'm not seeing?
After click on submit button in form with action="" page is reload and all data is lost. Pleas use:
<form action="javascript:void(0)">
instead of
<form action="">
This prevent page reload.
hey i need help with creating a delete button for my "notes" so it will delete it from the screen and the localstorage (u will notice i tried to make a delBtn function but with no success) i would appreciate if someone could post a fix to mine and explain me where i went wrong.
My JS
const tableBody = document.getElementById("tableBody");
const taskInfo = document.getElementById("taskInfo");
const taskDate = document.getElementById("taskDate");
const taskTime = document.getElementById("taskTime");
const delBtn = document.getElementById("delBtn")
let x = new Task("this is a test", "2021-04-14", "03:19");
let y = new Task("this is a 2nd test", "2021-04-14", "03:19");
//x.add();
//y.add();
let taskList = [
x, y, (new Task("this is a 3rd test", "2021-04-14", "03:19"))
];
if (localStorage.savedTaskList)
taskList = JSON.parse(localStorage.savedTaskList);
displayTable();
function displayTable() {
tableBody.innerHTML = "";
for (let task of taskList) {
const div = document.createElement("div");
div.setAttribute("class","taskZone");
const divTaskInfo = document.createElement("div");
divTaskInfo.setAttribute("class","taskInfo");
const divTaskDate = document.createElement("div");
divTaskDate.setAttribute("class","taskDate");
const divTaskTime = document.createElement("div");
divTaskTime.setAttribute("class","taskTime");
const delBtn = document.createElement("span");
delBtn.setAttribute("class","delBtn");
divTaskInfo.innerText = task.taskInfo;
divTaskDate.innerText = task.taskDate;
divTaskTime.innerText = task.taskTime;
div.append(divTaskInfo, divTaskDate, divTaskTime);
tableBody.appendChild(div);
}
}
delBtn.onclick = function delTask() {
delBtn.parentNode.removeChild(taskZoneElmToDel)
}
function addTask() {
if (taskInfo.value == '' || taskDate.value == '' || taskTime.value == '') {
return alert(`Please fill all the fields.`);
}else{newTask = new Task(taskInfo.value, taskDate.value, taskTime.value);
taskList.push(newTask);
localStorage.savedTaskList = JSON.stringify(taskList);
displayTable();
}
}
Thats the Html part of it
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Task Board</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
</head>
<body>
<div class="scaleable-wrapper" id="scaleable-wrapper">
<div class="very-specific-design" id="very-specific-design">
<header class="Title">
My Task Board
</header>
<div id="Input">
</br>
</br>
<form class="Form" id="formInfo">
<label for="taskInfo">Task Info:</label>
<input type="text" id="taskInfo" name="taskInfo" required autofocus></input></br>
<label for="taskDate">Task Date:</label>
<input type="date" id="taskDate" name="taskDate" required></input></br>
<label for="taskTime">Task Time:</label>
<input type="time" id="taskTime" name="taskTime" required></input></br>
<input type="submit" id="addTaskDiv" class="btn" value="Save" onclick="addTask()"></input>
<input type="reset" id="resetForm" class="btn"></input>
</form>
</br>
</br>
</div>
<div class="outNotes"></div>
<div class="tableBody">
<table>
<tbody id="tableBody">
</tbody>
</table>
</div>
</div>
</div>
<input type="button" id="delBtn">x</input>
</body>
<script src="Task.js"></script>
<script src="script2.js"></script>
</html>
I'm having trouble figuring out how to do this, and well, need help.
I'm trying to put my information into an array that's going to be shown and always be able to grow. I need help deleting specific entries into it, either by searching for one or by pointing a mouse and deleting it,
Is there any nice easy way to do it?
<!doctype html>
<html lang="sv">
<body>
<head>
<meta charset="UTF-8">
</title>
</head>
<body>
<input type="text" placeholder="Förnamn" id="name" autofocus>
<input type="date" id="pnummer" autofocus>
<input type="text" placeholder="Efternamn" id="enamn" autofocus>
<input type="button" value="mata in" onclick="register()">
<input type="button" value="visa" onclick="show()">
<script type="text/javascript">
array=[]
function register()
{
var fnamn = document.getElementById("name").value;
var enamn = document.getElementById("enamn").value;
var pnummer = document.getElementById("pnummer").value;
var p1 = new Person(fnamn,pnummer,enamn);
array.push(p1);
}
function Person(fnamn, pnummer, enamn)
{
this.fnamn=fnamn;
this.pnummer=pnummer;
this.enamn=enamn;
this.visa=function()
{
var panel ="Förnamn:"+" "+this.fnamn+" "+"Efternamn:"+" "+this.enamn+" "+"Personnummer:"+" "+this.pnummer+"<br>";
return panel;
}
}
function show(){
var showperson=document.getElementById("new");
showperson.innerHTML="";
var i=0;
while (array.length>i)
{
showperson.innerHTML+=array[i].visa()
i++;
}
}
</script>
<p id="new"></p>
<div id="panel"></div>
</body>
</html>
I am not 100% sure what you're trying to do or what some of those words mean but is this what you're trying to do?
var peopleTracker = {};
var peopleCounter = 0;
function addPerson()
{
// get the values
var firstName = document.getElementById("firstName").value.trim();
var lastName = document.getElementById("lastName").value.trim();
var birthday = document.getElementById("birthday").value.trim();
// make sure none are blank
if(firstName == "" || lastName == "" || birthday == "") return;
// give each person an ID so we can remove them later
var personID = ++peopleCounter;
peopleTracker[personID] = {
"firstName" : firstName,
"lastName" : lastName,
"birthday" : birthday
};
// add the person to the table
var row = document.getElementById("peopleList").insertRow();
row.insertCell().innerText = firstName;
row.insertCell().innerText = lastName;
row.insertCell().innerText = birthday;
row.insertCell().innerHTML = 'remove';
}
// delete a user from the tracker and remove the row
function removePerson(row, personID)
{
delete peopleTracker[personID];
row.parentNode.removeChild(row);
}
<!doctype html>
<html lang="sv">
<head>
<meta charset="UTF-8">
<title>the dingo ate my baby</title>
</head>
<body>
<input type="text" placeholder="First Name" id="firstName" autofocus>
<input type="text" placeholder="Sur Name" id="lastName" autofocus>
<input type="date" id="birthday" autofocus>
<input type="button" value="Add Person" onclick="addPerson()">
<br /><br />
<table border="1">
<thead>
<tr>
<th>First Name</th>
<th>Sur Name</th>
<th>Birthday</th>
<th>Action</th>
</tr>
</thead>
<tbody id="peopleList"></tbody>
</table>
</body>
</html>
A few thoughts:
If you're going to use an array to delete then you're going to need to use some unique ID to be able to find the person you want to delete. You cannot use the array index because that will change as you remove people from the array.
By using an object to store the users you can delete by using a unique ID that changes for each user added.
I jQuery is an option, you could find the index of your clicked <div> and delete the element with something like the following function:
$( "div.someIdYouGiveIt" ).click(function() {
var index = $( "div.someClassYouGiveIt" ).index( this );
array.splice(index, 1);
});