Update input value on table row from input value on row-1 - Javascript

Viewed 12

I'm new to javascript, jquery and I have doubts related to updating fields based on another input.

I have an html table form with multiple inputs for each row. Here's the html:

<table id="table">
   <thead>
       <tr>
           <td>Day</td>
           <td>Student Name</td>
           <td>Homework Time Left</td>
           <td>Homework Time</td>
           <td>Subject</td>
       </tr>
   </thead>
   <tbody>
   </tbody>

Each day a student can regiter its hours in this table form. The table is prefilled with every day of the current month, which means that it has more or less 22 rows from the start (only workdays). Each row represents a single day. I have the option to add a new row. For example on the first of january I studied 5h of English and 1h of Maths. To do it in the table form it would look something like:

    Date    | Student Name | Homework Time Left | Homework Time | Subject
2022-01-01  |   Harry      |    8               |  5            | English  

Every day, the maximum homework time to register is 8 hours. So, if a student studies more than one subject per day it has to add a new line like:

Date      | Student Name | Homework Time Left | Homework Time | Subject
2022-01-01|   Harry      |    3               |  1            | Maths

When adding a new line, the date field is empty. After inserting the date, it should look through all table rows and if it had a match for the same date, it updated the field "Homework time left". I'm able to do a for loop that finds the matching dates and updated this value. However, if I go to row 1 and change homework time from 5 to 2 then the following matching rows don't update this value. And vice versa if I delete a row it doesn't update the other matching rows on "homework time left".

When date input changes, this code is triggered:

var row = $(e).closest('tr');
var _date = $(row).find('input#dateInput').val();
var timeLeftInput = $(row).find('input#homeworkLeft');
var tleft;
for (var i = 0; i < document.querySelectorAll('input#homeworkLeft').length; i++) {
    var searchDate = document.querySelectorAll('input#homeworkLeft')[i].value;
    if (searchDate == _date) {
        var newTr = document.querySelectorAll('input#homeworkLeft')[i].closest('tr')
        var time = $(newTr).find('#homeworkLeft').val();
        var hour = $(newTr).find('#hours').val();
        if (time != "" && hour != "") {
            tleft = time - hour;

            if (tleft[i] < tleft[i - 1] && tleft > 0)
                tleft = tleft[i];
        }
    }
}

Depending on tleft value I update it in the input field that I want.

Does anyone know how to keep upddating homework time left value? I'm able to get this updated value from the above function because it comes from the date input on change. But if I change the homework time input it doesnt update the new rows

0 Answers
Related