4

This is my first question on here so go easy and apologies if this has been asked before but i could find no mention of it.

I am creating a purchase order system for the company i work for using PHP, MSSQL and a little JS/JQuery. I have a small form that i have created and although i cannot get it working on the JSFiddle it works in my environment, the problem i have is when i am trying to calculate the Quantity * Unit Cost + Delivery. This works on the first row but not on the dynamic rows i add after.

I can see why this is as there is no unique identifier for the input boxes, I have minimal knowledge of JS and JQuery so i am stuck in a rut here. Could anybody please point me in the right direction.

Many thanks in advance

JSFiddle of what i have so far

<div class="panel-body">
    <p> 
        <input type="button" class="btn btn-primary" value="Add Line" onclick="addRow('dataTable')"> 
        <input type="button" class="btn btn-danger" value="Remove Line" onclick="deleteRow('dataTable')"> 
    </p>
    <table width="100%">
        <thead>
            <tr>
                <th width="2%"></th>
                <th width="8%">Part Number</th>
                <th width="20%">Description</th>
                <th width="8%">Quantity</th>
                <th width="15%">Delivery</th>
                <th width="15%">Unit Cost</th>
                <th width="15%">Total Cost</th>
            </tr>
        </thead>
    </table>
    <table id="dataTable" width="100%" border="0">
      <tbody>
        <tr>
            <td width="2%"><input type="checkbox" name="chk[]"></td>
            <td width="8%">
                <input type="text" class="form-control" style="width: 90%;" name="partnumber[]">
             </td>
             <td width="20%">
                <input type="text" class="form-control" style="width: 90%;" required="required" name="description[]">
             </td>
             <td width="9%">
                <input type="number" class="form-control" style="width: 70%;" step="1" required="required" onblur="return Calculate();" id="quantity" name="quantity[]">
             </td>
             <td width="15%">
                <div class="input-group">
                    <span class="input-group-addon">
                        <i class="fa fa-gbp"></i>
                    </span>
                    <input type="number" pattern="^\d+(\.|\,)\d{2}$" class="form-control" onblur="return Calculate();" placeholder="0.00" step="0.01" style="width: 60%;" id="delivery" required="required" name="delivery[]">
                </div>
             </td>
             <td width="15%">
                <div class="input-group">
                    <span class="input-group-addon">
                        <i class="fa fa-gbp"></i>
                    </span>
                    <input type="number" pattern="^\d+(\.|\,)\d{2}$" class="form-control" onblur="return Calculate();" placeholder="0.00" step="0.01" style="width: 60%;" id="unitcost" required="required" name="unitcost[]">
                </div>
             </td>
             <td width="15%">
                <div class="input-group">
                    <span class="input-group-addon">
                        <i class="fa fa-gbp"></i>
                    </span>
                    <input type="number" pattern="^\d+(\.|\,)\d{2}$" class="form-control" placeholder="0.00" step="0.01" style="width: 60%;" id="totalcost[]" required="required" name="totalcost" disabled>
                </div>
             </td>
        </tr>
        </tbody>
    </table>
</div>

Javascript:

function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount < 20){                          // limit the user from creating fields more than your limits
    var row = table.insertRow(rowCount);
    var colCount = table.rows[0].cells.length;
    for(var i=0; i<colCount; i++) {
        var newcell = row.insertCell(i);
        newcell.innerHTML = table.rows[0].cells[i].innerHTML;
    }
}else{
     alert("Maximum number of purchase order rows reached");

}
}

function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
    var row = table.rows[i];
    var chkbox = row.cells[0].childNodes[0];
    if(null != chkbox && true == chkbox.checked) {
        if(rowCount <= 1) {                         // limit the user from removing all the fields
            alert("Cannot remove all purchase order lines");
            break;
        }
        table.deleteRow(i);
        rowCount--;
        i--;
    }
}
}
<script>
  function Calculate() {

    var quantity = document.getElementById("quantity").value;
    var delivery = document.getElementById("delivery").value;
    var unitcost = document.getElementById("unitcost").value;
    var total = (+quantity * +unitcost) + +delivery;
    document.getElementById("totalcost").value = total.toFixed(2);
  }

UPDATE: Brijesh got me on the right track, thanks to Anthony for tip using .on instead of .live. Working code at this JS fiddle http://jsfiddle.net/oczqkbpd/8/

$(document).ready(function () {
$(document).on("change", "input[name^=delivery],input[name^=quantity]", function () {
    $("input[name^=unitcost]").trigger("change");
});
$(document).on("change", "input[name^=unitcost]", function () {
    var unitcost = $(this).val() == "" ? 0 : $(this).val();
    var delivery = $(this).closest("td").siblings().find("input[name^=delivery]").val();
    var quantity = $(this).closest("td").siblings().find("input[name^=quantity]").val();
    var total = eval(quantity * unitcost) + Number(delivery);
    $(this).closest("td").siblings().find("input[name^=totalcost]").val(total.toFixed(2));
});
});
2
  • ids are conflicting when you replicate a row use class instead of ID.. and for event binding use jquery. Commented Apr 10, 2015 at 8:59
  • Hi Brijesh, could you help with an example of this? Like i said my knowledge of JS is not excellent, thanks Commented Apr 10, 2015 at 9:08

1 Answer 1

1

Using jquery 1.7 version i have implemented what you require using .live() function and on the change event of unitcost text box:

$("input[name^=delivery],input[name^=quantity], input[name^=unitcost]").live("input change", function(){
    $("input[name^=unitcost]").trigger("keyup");
});
    $("input[name^=unitcost]").live("keyup", function(){
        var unitcost = $(this).val()=="" ? 0 : $(this).val();
      var delivery = $(this).closest("td").siblings().find("input[name^=delivery]").val();
         var quantity = $(this).closest("td").siblings().find("input[name^=quantity]").val();
        var total = eval(quantity * unitcost) +parseInt(delivery);
    $(this).closest("td").siblings().find("input[name^=totalcost]").attr("disabled",false);
        $(this).closest("td").siblings().find("input[name^=totalcost]").val(total.toFixed(2));

        $(this).closest("td").siblings().find("input[name^=totalcost]").attr("disabled",true);


    });
});

Updated Fiddle

If you have any doubts please ask.

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

7 Comments

Thanks Brijesh. This works well however i seem to have to enter the unit cost last otherwise the calculation doesn't work, could you modify this so the calculation always takes places when changing the quantity, delivery or unit cost. Also the delivery cost is not adding on to the total and the total cost box is not disabled after the calculation. Thanks for your quick response
Hi Brijesh, the delivery still isn't being added on to the total cost. Also the delivery can be empty sometimes. thanks for your help
@LewisStancer can you check now?? updated the code .. keyup event is used now to triggered now instead ofchange and the text box is also disabled
Hi Brijesh. Delivery is not being added on to total cost still and the update is only working when i change the delivery box. Thanks
Any luck on this Brijesh? Would really appreciate the help finishing this off, 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.