0

I am in the process of creating a dynamic profit margin calculator for a small project I'm working on.

The brief

  1. A set of data is pulled from a database table using SQL and PHP
  2. after some sanity checks, the data is iterated out dynamically as rows in a standard HTML table
  3. In the process of iterating, we output some of the cells (specifically "cost of production" and "sale price") as inputs so the user can dynamically change the numbers around and see different margins
  4. The last cell of every row is a margin percentage that is calculated based on the values in the first two input fields

for pseudo code of the following process see snippet 1

The problem

The problem I am running in to is I am trying to use JS to dynamically update the margin field using an onChange() method for both of the inputs. The idea being that if the user updates one of the two fields, the values are read and the margin field updates.

attempts at a solution

  1. I have tried to output the ids in an array syntax to see if the values would store in an array like costOfProduction[]. This works in PHP syntax but not in JS from what I've seen
  2. I have tried writing a javascript function like updateTable(productionCost, salesCost, marginID) which would be called onChange() and passed the values. The only trouble is I wasn't able to find a way to pull values from adjacent cells into the onChange() call of the original cell.
  3. Scouring the SO forums for a similar fix. All the solutions I have seen have worked with a static single input and a submit button, but I need something more dynamic that does changes on individual inputs which are dynamically output.

code snippits

Snippit 1: output of table elements

    <table class="table table-hover table-responsive" id="marginTable">
        <thead>
          <tr>
            <th>product Name</th>
            <th>Sale Price</th>
            <th>production Cost</th>
            <th>Margin</th>
          </tr>
        </thead>

        <tbody>

            <?php 

                try {

                      /* connect to the database and get the data */

                        while (hasData){

                            echo 
                            '<tr>
                                <td>'.$dishName.'</td>
                                <td>
                                    <div class="input-group">
                                        <span class="input-group-addon">$</span>
                                        <input class="form-control" type="number" step="0.01" name="itemPrices[]" id="itemPrices" value="'($itemPrice).'" onchange="updateTable()">
                                    </div>
                                </td>
                                <td>
                                    <div class="input-group">
                                        <span class="input-group-addon">$</span>
                                        <input class="form-control" type="number" step="0.01" name="productionCost[]" id="productionCost" value="0.00" onchange="updateTable()">
                                    </div>
                                </td>
                                <td id="margins"><strong>0.00%</strong></td>
                            </tr>';

                          }

                        }

                    }

                } 

                echo '<script type="text/javascript">

                   function updateTable(){
                      /* javascript goes here */

                   }
                </script>';

            ?>

        </tbody>

    </table>

TL;DR

I need a way using JS that given if one of two inputs in a table is updated, a cell on that same row is calculated and updated based on what was input.

Thank you all so much for your time and help!

2
  • 1
    Your generated html is not valid, element ids should be unique. Currently, all your inputs have the same id. I suggest you add a sequential suffix to the id (itemPrices1, itemPrices2, ...), so when you detect a change on one of them, you can grab the other with the same suffix (itemPrices1 pairs with productionCost1 and vice versa). Commented Mar 24, 2020 at 23:42
  • Where is updateTable()? SO isn't a code-writing service, show us what you tried! :-) Also, to create a minimal, complete, and verifiable example - the problem is in your JS, not your PHP, so we don't need to see that. Show us a row or 2 of generated, static HTML, so we can try to help. Commented Mar 25, 2020 at 0:40

1 Answer 1

1

Much simpler to do. Remove the id and onchange handler. classes are much simpler to deal with in your case. Add a class to both your price and cost input fields as below.

<input class="form-control price" type="number" step="0.01" name="itemPrices[]" > // add class price

<input class="form-control cost" type="number" step="0.01" name="productionCost[]"> // add class cost

And in your last table data where you'll display the margin add a class margin to it as follows

<td class="margin"><strong>0.00%</strong></td>

Then with jquery you can acheive your results as

$(document).ready(function(){
$('table tbody').on('change','tr', function(){

    var price = $(this).find('input.price').val();
    var cost =  $(this).find('input.cost').val();
    var margin = price * cost; // test calculation

    $(this).find('td.margin').html("<strong>"+margin+"%</strong>");
});
});

Note this solution requires the jquery library

Hope this helps

Sign up to request clarification or add additional context in comments.

1 Comment

Beautiful! I've got a response and things are updating. Now I just need to tune the arithmetic but this should work! Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.