I do have a dynamic HTML table (rows can be added) and I "just" want to read the value in liters and convert it to USG when the user enters the value (get the value in liters , convert it and put it in the USG input field).
Dynamic HTML table
I've created a function that executes after each insertion of an ascending value:
_onFuelLiterInput(event) { // For all inputFields with name = fuelLiter $('#tankdaten .' + DEFINES.class.DYNAMIC_TABLE).find('tbody tr input.fuelLiter').each((index, element) => { let $element = $(element); let $ind = $(index); let value = 0; let USG = 0; // Read Value in Liters try { value = parseFloat($element.val()); } catch (e) { value = 0; } // ignore empty values if (isNaN(value)) { value=0; } // Convert Liter to USG USG = Math.round(value * 0.26417205235815 * 100)/100; // Update field with USG value $(event.target).closest('tr').find('.fuelUSG').val(USG); });
Each line in HTML contains a , as shown in the following example:
<td class="td-inputData"> <input class="inputFieldLiter fuelLiter" type="text" name="Fuel[<?php echo $i; ?>][fuelLiter]" data-name="fuelLiter" value="<?php echo $row['fuelLiter']; ?>" /> </td> <td class="td-inputData"> <input class="inputFieldLiter fuelUSG" type="text" name="Fuel[<?php echo $i; ?>][fuelUSG]" data-name="fuelUSG" value="<?php echo $row['fuelUSG']; ?>" /> </td>
Since the field name is the same on every line, I have trouble referencing the field in the same line, and $(event.target).closest('tr').find('.fuelUSG').val(USG ); didn't fix it as it lost the same woodiness.
Know how to do it?
I've tried $(event.target).closest('tr').find('.fuelUSG').val(USG); and hoped that the name "fuelUSG" would be updated. But unfortunately it doesn't work.
I must admit, I don't remember if I touched the key thing to make it work... (of course I added the event handler you were missing correctly)
Anyway, in this demo, in addition to the first function that only uses the template to add rows, it also considers the conversion logic in two steps so that:
The entire game is set up on a single loop over all
input.UsedFuel
, for each input in each row, the transformation is performed using only the value that was set at the beginning, and adding will perform the transformation Thekeyup
event listener displays in real time the line the user is editing.