Question

I would like the field "sub_total" to update as various fields are changed instead of it updating when one particular field is updated(namely: "add_on")

I have tried adding $(document).ready(function(){ to the top of the code, but it is not calculating at all if i add that.

HTML:

<td>Total Cost Full Day</td>
<input type="text" name="total_full" id="total_full"  />

<td>&nbsp;</td>
    <td>&nbsp;</td>

 <td>Total Cost Half Day</td>
<input type="text" name="total_half" id="total_half"  />

<td>&nbsp;</td>
    <td>&nbsp;</td>


<td>Addon Charge</td>
<input type="text" name="add_on" id="add_on"  />

<td>&nbsp;</td>
    <td>&nbsp;</td>


<td>Sub Total</td>
<input name="sub_total" type="text" id="sub_total" />​

JAVASCRIPT

//Calculate Sub Total


function calculateSubTotal() {

    var SubTotal = +total_full.value + +total_half.value + +add_on.value;

    document.getElementById("sub_total").value = isNaN(SubTotal) ? 0 : SubTotal;
}


document.getElementById("add_on").onchange = calculateSubTotal;
document.getElementById("add_on").onkeyup = calculateSubTotal;​
Was it helpful?

Solution

You need to be using jQuery to use something like $(document).ready. Otherwise it won't work.

That's my favorite method, but using something like window.onload works as well. See below... I also changed the calculation of your SubTotal. Unless you declared variables called total_full, total_half, and add_on, you still need to get the elements the same way you got them when assigning your events.

window.onload=function(){
//Calculate Sub Total


function calculateSubTotal() {

    var SubTotal = +document.getElementById("total_full").value + +document.getElementById("total_half").value + +document.getElementById("add_on").value;

    document.getElementById("sub_total").value = isNaN(SubTotal) ? 0 : SubTotal;
}


document.getElementById("add_on").onchange = calculateSubTotal;
document.getElementById("add_on").onkeyup = calculateSubTotal;
document.getElementById("total_full").onchange = calculateSubTotal;
document.getElementById("total_full").onkeyup = calculateSubTotal;
document.getElementById("total_half").onchange = calculateSubTotal;
document.getElementById("total_half").onkeyup = calculateSubTotal;

}

OTHER TIPS

If your function works with add_on fields, you should bind that function on each of the fields you want calculated. Just like you did for the "add_on".

So each time you change one of the fields, your function will update the subtotal.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top