0

I have been looking for awhile but can not figure how to code the below example:

Enter in Weight of Cans:

(ADD BUTTON) - Purpose to add another input field to enter in additional weight field
Input Field = Weight 1 = 5
Input Field = Weight 2 = 5
Input Field = Weight 3 = 10  
Input Field = Weight i = ? (after clicking on ADD)

Then I want in real time for the Total Weight to be calculated so in this case it would be 20 and finaly an estimate of Total Cans with this formula (Total Weight * 150) so in the example Total Cans would be 3000.

I want to use HTML Form and Javascript but I do not know how to handle the Add Button feature so the Total Weight and Total Cans can be calcualted in real time. I am thinking of an array but can not figure the syntax.

Any advice or assistance would be greatly appreicated.

2
  • Post the the code you have so far Commented Oct 23, 2014 at 19:08
  • This question is not specific enough. High level you could use a onchange event listener for each form element that calls a JS function to perform the calculations you want and add the data to some other dom element. Commented Oct 23, 2014 at 19:39

1 Answer 1

2

I'm normally against this, but it seems as though you genuinely need help, so here it is. Keep in mind, this is very basic and there are better ways to do this, but I wanted to keep it very simple for you since you're just starting out. First - you really don't need a button. If you want a button, you can assign the function to a button action, but this code automatically calculates the total for you. Also, you'll want to add in some validation, this quick example assumes that everyone always just enters a number like they're supposed to... which never happens, so you'll want to look into some validation as well.

Here is a working example: http://jsfiddle.net/813dL6d3/1/

And the code:

HTML:

<input type="text" id="weight1" onblur="calculateForm();" /><br />
<input type="text" id="weight2" onblur="calculateForm();" /><br />
<input type="text" id="weight3" onblur="calculateForm();" /><br />
<input type="text" id="weightTotal" />

Javascript:

var calculateForm = function () {
    document.getElementById("weightTotal").value =
    (
        Number(document.getElementById("weight1").value) +
        Number(document.getElementById("weight2").value) +
        Number(document.getElementById("weight3").value)
    ) * 150;
};
Sign up to request clarification or add additional context in comments.

1 Comment

This is perfect I just needed a starting point I will make sure to work on the code and make it better thank you for your help

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.