Creating and saving new tr elements with JS

114 Views Asked by At

I’m fairly new to coding, especially JS. I’m building a program meant to calculate input and put the result (along with the date) into a table. There should be a new entry in the table every time there is new input. Whenever the page is reloaded, the table’s data should be saved and retrieved.

The problem I’m having now is that only the first entry is saved. All the data in the table must be saved. Does anybody have a suggestion? Thanks.

Here's my code:

// variables

const input = document.getElementById('input');

//buttons

const enter = document.getElementById('enter-value');
const log = document.getElementById("log-value");
const save = document.getElementById("save-value");
const done = document.getElementById("done-button");

//log areas

const itemHolder = document.getElementById('item-holder');
const totalMarker = document.getElementById("grand-total");

// messagges

const negativeValueMessage = document.getElementById('value-message-negative');
const positiveValueMessage = document.getElementById('value-message-positive');
const doneMessage = document.getElementById('done');

//other

const tool = document.getElementById('tool');
const date = new Date();

//input testing code

function checkInput (){
    input.addEventListener('input', function(){
        if(input.value < 0 ){
           negativeValueMessage.style.display = "block";
           positiveValueMessage.style.display = "none";
           enter.style.display = "block";
           enter.disabled = false;
           enter.style.opacity = "100%";
        }
        else if (input.value > 0) {
            negativeValueMessage.style.display = "none";
            positiveValueMessage.style.display = "block";
            enter.style.display = "block";
            enter.disabled = false;
            enter.style.opacity = "100%";
        }
        else {
            negativeValueMessage.style.display = "none";
            positiveValueMessage.style.display = "none";
            enter.disabled = true;
            if(enter.disabled){
                enter.style.opacity = '60%';
            }
        }
    });
}
checkInput();

// input reception

function useInput (){
    enter.addEventListener('click', function(){
        enter.style.display = 'none';
        log.style.display = 'block';
        inputDisalowed();
        log.addEventListener('click', function(){
            const addValues = Number(input.value) + Number(totalMarker.value);
            const total = addValues;
            totalMarker.value = total;
            function newInfo(){
                itemHolder.innerHTML += '<tr><td id="date">' + dateHolder + '</td><td id="amount">$' + totalMarker.value + '</td></tr>';
            }
            newInfo();
            log.style.display = 'none';
            save.style.display = 'block';
            save.addEventListener('click', function(){
                doneMessage.style.display = "grid";
                tool.style.display = 'none';
                const dateData = document.getElementById('date').innerText;
                const amountData = document.getElementById('amount').innerText;
                const dataArray = [dateData, amountData];
                localStorage.setItem('savedDate', (dataArray[0]));
                localStorage.setItem('savedAmount', dataArray[1]);
                localStorage.setItem('savedTotal', Number(totalMarker.value));
                done.addEventListener('click', function(){
                    reloadPage();
                });
            });
        });
    });
}
useInput();
retrieveOnReload();
const dateHolder = monthFixedValue() + '/' + date.getDate() + '/' + date.getFullYear();

function monthFixedValue (){
    return date.getMonth() + 1;
}
function inputDisalowed (){
    input.addEventListener('input', function(){
        alert("You have already input your value. Inputing again will always restart the proccess.");
        location.reload();
    });
}
function retrieveOnReload(){
    window.addEventListener('DOMContentLoaded', function(){
    const retrievedDate = localStorage.getItem('savedDate');
    const retrieveAmount = localStorage.getItem('savedAmount');
    itemHolder.innerHTML += '<tr><td id="date">' + retrievedDate + '</td><td id="amount">' + retrieveAmount + '</td></tr>';});
    totalMarker.value = Number(localStorage.getItem('savedTotal'));
};
function reloadPage() {
    window.location.href = window.location.href;
}
*{
    box-sizing: border-box;
    font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
}
::-webkit-scrollbar{
    width:13px;
}
::-webkit-scrollbar-track{
    background: rgb(160,180,190);
    border-radius: 5px;
}
::-webkit-scrollbar-thumb{
    background: rgb(120,140,150);
    border-radius: 10px;
}
body {
    background-image: url(/Background.svg);
    display: grid;
    width: 100vw;
    justify-content: center;
    margin: 0;
    background-position: center;
    align-content: center;
    justify-items: center;
}
h1{
    border: 1px solid black;
    display: flex;
    justify-content: center;
    align-items: center;
    background-image: linear-gradient(
        rgb(150,170,180),
        rgb(120,140,150)
    );
    border-radius: .5vw;
    margin-bottom: 10px;
    width: 80vw;
    height: 70px;
    min-width: 400px;
    font-family:'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
    color: rgb(20,20,90);
    font-size: 40px;
    border: none;
    margin-top: -150px;
    margin-left: -20px;
}
main{
    display: grid;
    align-items: center;
    justify-items: center;
    background: linear-gradient(
        rgb(150,170,180) 20%,
        rgb(120,140,150) 
    );
    border-radius: .5vw;
    margin-top: 10px;
    padding: 20px;
    width: 80vw;
    min-width: 400px;;
}
.inputs {
    margin: 20px;
    width: 90%;
    display: flex;
    justify-content: center;
}
input {
    border: none;
    background-color: rgb(30,90,130);
    color: rgb(10,10,50);
    height: 35px;
    width: 220px;
    font-family:'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
    font-size: 15px;
    border-bottom: 2px solid rgb(20,80,100);
    border-radius: .2vw;
    margin-right: 3px;
    &::placeholder{
        color: rgb(100,140,180);
        font-family:'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
        font-size: 15px;
        font-weight: 900;
    }
}
#enter-value, #save-value, #log-value{
    border: none;
    border-radius: .2vw;
    background: rgb(20,80,180);
    font-size: 20px;
    font-weight: bolder;
    color: rgb(10,10,50);
    margin-left: 3px;
    &:hover{
        background: rgb(10,70,170);
    }
    &:active{
        background: rgb(20,80,180);
    }
}
#enter-value{
    display: none;
}
#save-value{
    display: none;
}
#log-value{
    display: none;
}
.value-message{
    color: rgb(30,40,100);
    display: none;
    margin-bottom: -20px;
}
label{
    text-align: center;
    font-weight: bolder;
    display: flex;
    align-items: baseline;
    font-size: 35px;
    
}
#grand-total{
    height: 40px;
    width: 150px;
    margin-bottom: 30px;
    margin-top: 0px;
    background: rgb(10,10,100);
    color: rgb(150,170,180);
    display: grid;
    align-content: center;
    text-align: center;
    font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
    border-radius: 2px;
    font-weight: bolder;
    font-size: 35px;
}
.table-window{
    height: 100px;
    width: 100%;
    display: grid;
    justify-items: center;
    align-items: center;
    overflow-y: scroll;
}
table{
    background-color: rgb(60,120,160);
    border-style: none;
    border-collapse: collapse;
}
.heading-row{
    background: rgb(100,160,200);
    height: 40px;
    width: 750px;
}
th{
    border: 0;
    width: 170px;
}
td{
    text-align: center;
    padding: 4px;
    width: 170px;
}
.th1,
.th2,
.th3{
    border-right: 2px solid rgb(170,170,255);
}
.td1,
.td2,
.td3{
    border-right: 2px solid rgb(170,170,255);
}
#done{
    position: absolute;
    display: grid;
    justify-items: center;
    display: none;
}
#done-img-holder{
    display: flex;
    justify-content: center;
    align-content: center;
    width: 100%;
    height: 100%;
}
#done-img-holder > img{
    width: 490px;
    display: grid;
    margin-top: -30px;
}
#done-info-holder{
    display: grid;
    justify-items: center;
    width: 400px;
    height: 170px;
    background: linear-gradient(
        rgb(180,180,190),
        rgb(140,140,150)
    );
    align-content: center;
    border-radius: .5vw;
}
#done-info-holder > p{
    font-size: 20px;
    color: rgb(10,70,160);
    font-weight: 900;
}
#done-info-holder > button{
    height: 50px;
    width: 130px;
    font-size: 30px;
    font-weight: 900;
    background: rgb(10,10,100);
    border: none;
    border-radius: 30px;
    color: rgb(120,140,150);
    &:hover{
        background: rgb(120,140,150);
        color: rgb(10,10,100);
    }
    &:active{
        background: rgb(10,10,100);
        color: rgb(120,140,150);
    }
}
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="veiwport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="FinanceTool.css">
    <title>Finance_Tool</title>
</head>
<body>
    <main id="tool">
            <h1 class="heading">Simple Finance Tool</h1>
        <p id="value-message-negative" class="value-message">Your number is negative. This will be calculated as a financial loss.</p>
        <p id="value-message-positive" class="value-message">Your number is positive. This will be calculated as a financial gain.</p>
        <div class="inputs">
            <input type='number' id="input" class="input" placeholder="Input financial loss or gain." min="0"/>
            <button type="button" id="enter-value">Enter</button>
            <button type="button" id="log-value">Log Change</button>
            <button type="button" id="save-value">Save Change</button>
        </div>
        <label for="grand-total">$<input id="grand-total" disabled/></label>
        <div class="table-window">
            <table id="item-holder">
                <tr class="heading-row">
                    <th class="th1">Date</th>
                    <th class="th4">Total After Change</th>
                </tr>
            </table>
            
            
        </div>
        
    </main>
    <div id="done">
        <div id="done-img-holder">
            <img src="/Finance Tool/check-circle-svgrepo-com.svg"/>
        </div>
        <div id="done-info-holder">
            <p>All done! You're entry is complete.</p>
            <button id="done-button">Done</button>
        </div>
    </div>
    <script src="FinanceTool.js"></script>
</body>
</html>

Also here’s a link to the code in codePen(note: due to a peculiarity of codePen, the code will not work properly in it, but you can copy it from codePen to your IDE).

codePenProjectLink

1

There are 1 best solutions below

5
Mehdi On BEST ANSWER

Below is a starter for you to see how we can proceed if I properly understood your needs. I made 2 type of array, simple array (dateArray and amountArray) and dailyInputArray = array of object(dailyInput ). Also note that for a better and safer storage you need to store in MySQL database. NB I think because of using localstorage the code snippet does not seem to work on SO pls check it in your code editor.

let amountArray=[]
let dateArray=[]
let dailyInput={}
let dailyInputArray=[]
let retrieveDailyInputValues = localStorage.getItem('DailyInputValues');
retrieveDailyInputValues = JSON.parse(retrieveDailyInputValues)
console.log(retrieveDailyInputValues)
if(retrieveDailyInputValues && retrieveDailyInputValues.length!=0){
    dailyInputArray=retrieveDailyInputValues
}else{
    dailyInputArray=[]
}


const input = document.getElementById('input');

//buttons

const enter = document.getElementById('enter-value');
const log = document.getElementById("log-value");
const save = document.getElementById("save-value");
const done = document.getElementById("done-button");

//log areas

const itemHolder = document.getElementById('item-holder');
const earningHolder = document.getElementById('earning-holder');
const totalMarker = document.getElementById("grand-total");

// messagges

const negativeValueMessage = document.getElementById('value-message-negative');
const positiveValueMessage = document.getElementById('value-message-positive');
const doneMessage = document.getElementById('done');

//other

const tool = document.getElementById('tool');
const date = new Date();
const dateHolder = monthFixedValue() + '/' + date.getDate() + '/' + date.getFullYear();
function monthFixedValue (){
    return date.getMonth() + 1;
}


//input testing code

function checkInput (){
    input.addEventListener('input', function(){
        if(input.value < 0 ){
           negativeValueMessage.style.display = "block";
           positiveValueMessage.style.display = "none";
           enter.style.display = "block";
           enter.disabled = false;
           enter.style.opacity = "100%";
        }
        else if (input.value > 0) {
            negativeValueMessage.style.display = "none";
            positiveValueMessage.style.display = "block";
            enter.style.display = "block";
            enter.disabled = false;
            enter.style.opacity = "100%";
        }
        else {
            negativeValueMessage.style.display = "none";
            positiveValueMessage.style.display = "none";
            enter.disabled = true;
            if(enter.disabled){
                enter.style.opacity = '60%';
            }
        }
    });
}
checkInput();

// input reception

function useInput (){
    enter.addEventListener('click', function(){
        enter.style.display = 'none';
        log.style.display = 'block';
        inputDisalowed();
        log.addEventListener('click', function(){
            dailyInput.date = dateHolder
            dailyInput.earnings = input.value
            dailyInputArray.push(dailyInput)
            console.log(dailyInput)
            console.log(dailyInputArray)
            localStorage.setItem('DailyInputValues', JSON.stringify(dailyInputArray)); 
            const addValues = Number(input.value) + Number(totalMarker.value);
            const total = addValues;
            totalMarker.value = total;
            function newInfo(){
                itemHolder.innerHTML += '<tr><td id="date">' + dateHolder + '</td><td id="amount">$' + totalMarker.value + '</td></tr>';
            }
            newInfo();
            log.style.display = 'none';
            save.style.display = 'block';
            save.addEventListener('click', function(){
                doneMessage.style.display = "grid";
                tool.style.display = 'none';
                let dateData = document.getElementById('date').innerText; 
                let amountData = document.getElementById('amount').innerText; 
                dateArray.push(dateData) 
                amountArray.push(amountData) 
                localStorage.setItem('savedDate', JSON.stringify(dateArray)); 
                localStorage.setItem('savedAmount', JSON.stringify(amountArray)); 
                // const dataArray = [dateData, amountData];
                // localStorage.setItem('savedDate', (dataArray[0]));
                // localStorage.setItem('savedAmount', dataArray[1]);
                localStorage.setItem('savedTotal', Number(totalMarker.value));
                // done.addEventListener('click', function(){
                //     reloadPage();
                // });
            });
        });
    });
}
useInput();
retrieveOnReload();

function inputDisalowed (){
    input.addEventListener('input', function(){
        alert("You have already input your value. Inputing again will always restart the proccess.");
        // location.reload();
    });
}
function retrieveOnReload(){
    window.addEventListener('DOMContentLoaded', function(){
        for(let i=0; i < dateArray.length ; i++){ 
            let retrievedDate = localStorage.getItem('dateArray'); 
            retrievedDate = JSON.parse(retrievedDate) 
            let retrieveAmount = localStorage.getItem('amountArray'); 
            retrieveAmount = JSON.parse(retrieveAmount)
            itemHolder.innerHTML += '<tr><td class="date">' + retrievedDate[i] + '</td><td class="amount">' + retrieveAmount[i] + '</td></tr>';
         }

         for(let j=0; j < retrieveDailyInputValues.length ; j++){ 
            let retrieveEarningdDate = dailyInputArray[j].date 
            let retrieveDailyEarning = dailyInputArray[j].earnings 
            earningHolder.innerHTML += '<tr><td class="date">' + retrieveEarningdDate + '</td><td class="amount">' + retrieveDailyEarning + '</td></tr>';
         }
    // const retrievedDate = localStorage.getItem('savedDate');
    // const retrieveAmount = localStorage.getItem('savedAmount');
    // itemHolder.innerHTML += '<tr><td id="date">' + retrievedDate + '</td><td id="amount">' + retrieveAmount + '</td></tr>';
});
    totalMarker.value = Number(localStorage.getItem('savedTotal'));
};
// function reloadPage() {
//     window.location.href = window.location.href;
// }
*{
  box-sizing: border-box;
  font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
}
::-webkit-scrollbar{
  width:13px;
}
::-webkit-scrollbar-track{
  background: rgb(160,180,190);
  border-radius: 5px;
}
::-webkit-scrollbar-thumb{
  background: rgb(120,140,150);
  border-radius: 10px;
}
body {
  background-image: url(/Background.svg);
  display: grid;
  width: 100vw;
  justify-content: center;
  margin: 0;
  background-position: center;
  align-content: center;
  justify-items: center;
}
h1{
  border: 1px solid black;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: linear-gradient(
      rgb(150,170,180),
      rgb(120,140,150)
  );
  border-radius: .5vw;
  margin-bottom: 10px;
  width: 80vw;
  height: 70px;
  min-width: 400px;
  font-family:'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
  color: rgb(20,20,90);
  font-size: 40px;
  border: none;
  margin-top: -150px;
  margin-left: -20px;
}
main{
  display: grid;
  align-items: center;
  justify-items: center;
  background: linear-gradient(
      rgb(150,170,180) 20%,
      rgb(120,140,150) 
  );
  border-radius: .5vw;
  margin-top: 10px;
  padding: 20px;
  width: 80vw;
  min-width: 400px;;
}
.inputs {
  margin: 20px;
  width: 90%;
  display: flex;
  justify-content: center;
}
input {
  border: none;
  background-color: rgb(30,90,130);
  color: rgb(10,10,50);
  height: 35px;
  width: 220px;
  font-family:'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
  font-size: 15px;
  border-bottom: 2px solid rgb(20,80,100);
  border-radius: .2vw;
  margin-right: 3px;
  &::placeholder{
      color: rgb(100,140,180);
      font-family:'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
      font-size: 15px;
      font-weight: 900;
  }
}
#enter-value, #save-value, #log-value{
  border: none;
  border-radius: .2vw;
  background: rgb(20,80,180);
  font-size: 20px;
  font-weight: bolder;
  color: rgb(10,10,50);
  margin-left: 3px;
  &:hover{
      background: rgb(10,70,170);
  }
  &:active{
      background: rgb(20,80,180);
  }
}
#enter-value{
  display: none;
}
#save-value{
  display: none;
}
#log-value{
  display: none;
}
.value-message{
  color: rgb(30,40,100);
  display: none;
  margin-bottom: -20px;
}
label{
  text-align: center;
  font-weight: bolder;
  display: flex;
  align-items: baseline;
  font-size: 35px;
  
}
#grand-total{
  height: 40px;
  width: 150px;
  margin-bottom: 30px;
  margin-top: 0px;
  background: rgb(10,10,100);
  color: rgb(150,170,180);
  display: grid;
  align-content: center;
  text-align: center;
  font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
  border-radius: 2px;
  font-weight: bolder;
  font-size: 35px;
}
.table-window{
  height: 100px;
  width: 100%;
  display: grid;
  justify-items: center;
  align-items: center;
  overflow-y: scroll;
}
table{
  background-color: rgb(60,120,160);
  border-style: none;
  border-collapse: collapse;
}
.heading-row{
  background: rgb(100,160,200);
  height: 40px;
  width: 750px;
}
th{
  border: 0;
  width: 170px;
}
td{
  text-align: center;
  padding: 4px;
  width: 170px;
}
.th1,
.th2,
.th3{
  border-right: 2px solid rgb(170,170,255);
}
.td1,
.td2,
.td3{
  border-right: 2px solid rgb(170,170,255);
}
#done{
  position: absolute;
  display: grid;
  justify-items: center;
  display: none;
}
#done-img-holder{
  display: flex;
  justify-content: center;
  align-content: center;
  width: 100%;
  height: 100%;
}
#done-img-holder > img{
  width: 490px;
  display: grid;
  margin-top: -30px;
}
#done-info-holder{
  display: grid;
  justify-items: center;
  width: 400px;
  height: 170px;
  background: linear-gradient(
      rgb(180,180,190),
      rgb(140,140,150)
  );
  align-content: center;
  border-radius: .5vw;
}
#done-info-holder > p{
  font-size: 20px;
  color: rgb(10,70,160);
  font-weight: 900;
}
#done-info-holder > button{
  height: 50px;
  width: 130px;
  font-size: 30px;
  font-weight: 900;
  background: rgb(10,10,100);
  border: none;
  border-radius: 30px;
  color: rgb(120,140,150);
  &:hover{
      background: rgb(120,140,150);
      color: rgb(10,10,100);
  }
  &:active{
      background: rgb(10,10,100);
      color: rgb(120,140,150);
  }
}
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="veiwport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="FinanceTool.css">
    <title>Finance_Tool</title>
</head>
<body>
<main id="tool">
    <h1 class="heading">Simple Finance Tool</h1>
<p id="value-message-negative" class="value-message">Your number is negative. This will be calculated as a financial loss.</p>
<p id="value-message-positive" class="value-message">Your number is positive. This will be calculated as a financial gain.</p>
<div class="inputs">
    <input type='number' id="input" class="input" placeholder="Input financial loss or gain." min="0"/>
    <button type="button" id="enter-value">Enter</button>
    <button type="button" id="log-value">Log Change</button>
    <button type="button" id="save-value">Save Change</button>
</div>
<label for="grand-total">$<input id="grand-total" disabled/></label>
<div class="table-window">
    <table id="item-holder">
        <tr class="heading-row">
            <th class="th1">Date</th>
            <th class="th4">Total After Change</th>
        </tr>
    </table>
    <table id="earning-holder">
      <tr class="heading-row">
          <th class="th1">Date</th>
          <th class="th4">Earning</th>
      </tr>
  </table>
    
</div>

</main>
<div id="done">
<div id="done-img-holder">
    <img src="/Finance Tool/check-circle-svgrepo-com.svg"/>
</div>
<div id="done-info-holder">
    <p>All done! You're entry is complete.</p>
    <button id="done-button">Done</button>
</div>
</div>
</body>
</html>