Update values when adding a new row - only if the colum date and student name is already present in table - html and javascript

Viewed 23

I'm new to the JS language and I don't know how to do something. I have a table such as:

<table id="table">
       <thead>
           <tr>
               <td>Day</td>
               <td>Student Name</td>
               <td>Student Food Credit Used</td>
               <td>Student Food Credit</td>
           </tr>
       </thead>
       <tbody>
       </tbody>
   </table>

Above this table I have a button, "Add row". Everyday this table needs to be updated with the students food credit values. The column "Student Food credit Left" is a helper column, which serves just to help the user see how much credit the student has. For example: A student always starts with a credit of 100. So, in the Food credit left it should appear at first 100. Then if the student buys something then this value should be updated.

This row should be updated multiple times a day. For every purchage the student makes it's a new row that needs to be added and the credit left column should be updated with the one above it.

     Date     | Student Name | Credit Left | Credit Used
  2022-09-01  |   Harry      |     100     |  50

Then when adding a new row, in the same day:

     Date     | Student Name | Credit Left | Credit Used
  2022-09-01  |   Harry      |     50      |  10

It's important to mention that, this table of rows have multiple students. If the table is saved to the database before inserting a new row in the same day, I'm able to see how many credit left the student has. However, if I just keep adding rows, in the same day, before adding to DB, I'm not able to keep updating the credit with javascript.

EDIT

I followed the advice of the comment that I marked as the answer. So, I looped through all the rows in my table to see if I found a match to the value I wanted. If so, I put it in an array. Then I looped through this array to find the smallest number and kept updating it everytime I added a new row

1 Answers

I understand your data is coming from a database and your are parsing it to build this table, so you can validate the present based on user data in the array and validate it by the array, or you can do it only with JS, getting all data from the table, parsing it to an array and then parsing it.

Eg.: If the array coming from the database is like this

[
 {
  username: "john",
  date: 0000-00-00,
  credits_left: 100,
  credits_used: 50,
 }
]

In this case you can use the array method findIndex to get the user name and date, and if it's found you change the array

https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex

If the value returned it's -1 so the index was not founded and you can return the function without change the table data

Related