0

the following works in Jfiddle-but when i use it in original form, the total_full and total_half fields are calculated automatically from other fields, and therefore do not have a keyup or keydown event? therefore the "sub_total" field is not calculating when the "total_full" and total_half fields are updated?

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>

JAVASCRIPT

//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;
calculateSubTotal;
document.getElementById("total_half").onchange = calculateSubTotal;
document.getElementById("total_half").onkeyup = calculateSubTotal;

http://jsfiddle.net/newbie123/ue62p/5/

7
  • Where are you putting the javascript code in your file? Commented Jun 17, 2012 at 1:18
  • @FabrícioMatté within script tags at the bottom of the HTML Commented Jun 17, 2012 at 1:19
  • It should work then. Check your JS console (IE/Chrome: F12; Firefox: Ctrl+Shift+K) and check if there are any errors in the console. (open console, refresh page, type some numbers in the fields) Commented Jun 17, 2012 at 1:22
  • @FabrícioMatté: there are no errors in the console? I can calculate the sub total field if i add the event on another field which I input text into, but it only wont work on the fields which are automatically calculated? Commented Jun 17, 2012 at 1:24
  • 1
    Oh no problem, I just figured it a couple mins ago that you wanted your function to fire when updating your fields through JS, and yes, your answer is right, you have to call it manually unless adding eventListeners. :) Commented Jun 17, 2012 at 1:33

1 Answer 1

1

onChange only fires when a user updates the value. If you want that functionality, you're going to have to add calculateSubTotal to the events where total_full and total_half are updated.

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

Comments

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.