Live calculations using Javascript from inputs that gets populated dynamically

Viewed 49

I am trying to do live calculations from inputs that gets populated dynamically. With my current code, the calculations only work when i edit the input fields. What needs to happen, once a product gets selected then the input fields gets populated with a price and levy, then the calculation automatically happens.

<form action="" method="POST">
    <select style="width: 50%;" name="item" id="item"> 
        <option value="" disabled selected>Click to See Products</option>

    <?php 

        $records = mysqli_query($conn_test, "SELECT * FROM live_calculation");
        while ($data = mysqli_fetch_array($records)) {

            $price = $data['price'];
            $product = $data['product'];
            $levy = $data['levy'];
            
            echo '<option value="' . $data['product'] . '"  
            data-price="' . $data['price'] . '" 
            data-levy="' . $data['levy'] . '" >'
           . $data['product'] . '</option>';    
        }
    ?>
    </select>
    <br>
    <br>

    <div id="orders">
        <label>Price</label>
        <input class="form-control price" type='text' data-type="price" id='price' name='price'/>
        <br>
        <br>

        <label>Levy</label>
        <input class="form-control levy" type='text' data-type="levy" id='levy' name='levy'/>
        <br>
        <br>
        
        <label>Total</label>
        <input class="form-control total" type='text' id='total' name='total'/>

    </div>
</form>

Get input data values

<script>

// Get input data values
document.addEventListener('click', function(event) {  
    let mySelect = document.getElementById("item");
    if (mySelect !== null) {
        mySelect.addEventListener("change", () => document.getElementById("price").value = mySelect.options[mySelect.selectedIndex].getAttribute("data-price"))
        
        mySelect.addEventListener("change", () => document.getElementById("levy").value = mySelect.options[mySelect.selectedIndex].getAttribute("data-levy"))

    }
});
</script>

Script to do the calculations

<script>

// Script to do the calculations 

document.addEventListener('change', function() { 
    $("#orders").on('input', 'input.price,input.levy', function() {
        getTotalCost($(this).attr("for"));
    });

    function getTotalCost() {
        var price = document.getElementById('price').value;
        var levy = document.getElementById('levy').value;
        var total = price / levy;

        $('#total').val(total);
    }
});
</script>
0 Answers
Related