Home  >  Q&A  >  body text

JQuery - On-the-fly calculations/conversions in dynamic tables

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.

P粉364642019P粉364642019181 days ago408

reply all(1)I'll reply

  • P粉741223880

    P粉7412238802024-04-04 10:04:57

    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 lowest layer is only responsible for obtaining string values parameters and return the conversion result as a number
    • Use specific input elements as the upper layer of parameters itself; still get its value as a string; pass it to the conversion function described earlier and sets its sibling inputs with values Converted

    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 The keyup event listener displays in real time the line the user is editing.

    //adds a number of rows to the main table (for the sake of the demo)
    function addRows(n, random = true){  
      const max = 1000;
      for(let i=1;i<=n;i++){
        const row = $('#tableRow')[0].content.cloneNode(true);
        if(random){
          const rndFuel = Math.floor(Math.random() * max);
          $(row).find('.UsedFuel').val(rndFuel);
        }
        $('.table tbody').append(row);
      }  
    }
    //adds 10 rows
    addRows(5, false); //5 with the default value = 100
    addRows(5, true); //5 with random values max 1000
    
    //-------------------------
    
    //initialize the page.. given the table in #tankdaten .table
    $('#tankdaten .table')
      //finds all the input.UsedFuel in tbody rows
      .find('tbody tr input.UsedFuel')
        //and for each one of them
        .each((index, element) => {
          //performs the conversion for the initial value (set with the value attribute)
          performConversion(element);
          //adds the keyup event handler to the element, that..
          $(element).on('keyup',(event)=>{        
            //will perform the conversion to the element triggering the event
            performConversion( $(event.target) );
          });
        });
    
    //starting from the litersInputElement passed,
    //it performs the conversion and sets the value of the sibling .fuelUSG
    function performConversion(litersInputElement){
      const USG = convertLitersToUSG($(litersInputElement).val());
      $(litersInputElement).closest('tr').find('.fuelUSG').val(USG);
    }
    
    //given the amount of liters (as string) returns the USG as number
    function convertLitersToUSG(liters) {
      let parsed = parseFloat(liters);
      if (isNaN(parsed))
        parsed = 0;
    
      return Math.round(parsed * 0.26417205235815 * 100)/100;
    }
    sssccc
    
    

    reply
    0
  • Cancelreply