adding up a total

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Samir

    #1

    adding up a total

    Here is a sample form that I just made up. I would like a somekind of
    script that when each button is checked or unchecked to dynamicly add or
    subtract the total. If anyone can help, thanks alot.

    <html>

    <head>

    <title>Testin g addition of javascript</title>
    </head>

    <body>

    <form method="POST" action="">
    <p><input type="checkbox" name="C1" value="50">item 1 $50</p>
    <p><input type="checkbox" name="C2" value="10">item 2 $10</p>
    <p><input type="checkbox" name="C3" value="30">item 3 $30</p>
    <p><input type="checkbox" name="C4" value="60">item 4 $60</p>
    <p>Total $ totalhere</p>
    </form>

    </body>
    <script type="text/javascript">

    </script>
    </html>
  • Fred Oz

    #2
    Re: adding up a total

    Samir wrote:[color=blue]
    > Here is a sample form that I just made up. I would like a somekind of
    > script that when each button is checked or unchecked to dynamicly add or
    > subtract the total. If anyone can help, thanks alot.[/color]
    [snip]

    Add an "onchange" function to each checkbox that calls a function to
    cycle through the checkboxes and add up those that are checked, e.g.:

    <p><input type="checkbox" name="C1" value="50"
    onchange="write Total(this.form ,'total');">ite m 1 $50</p>

    then write the total to the paragraph.

    function writeTotal(x,y) {
    var total = 0;
    for (var i=0;i<x.element s.length; i++) {
    if (x.elements[i].type == 'checkbox'
    && x.elements[i].checked) {
    total += +x.elements[i].value;
    } }
    document.getEle mentById(y).inn erHTML = total;
    }

    Of course this is just a minimal example, you need to add feature
    detection and handle cases where the user has JavaScript disabled.

    You'll need a custom reset button because the normal one will not
    change the total in the paragraph:

    <input type="button" value="Clear all"
    onclick="this.f orm.reset();wri teTotal(this.fo rm,'tot');">

    Also, you need to ensure that when the page is re-loaded, the form is
    re-set as some browsers will clear the check boxes but not update the
    paragraph text (or vice versa) - say an 'onload' function to reset the
    form.

    You can add an id to the para, or put in a <span> with an id and just
    write the number:

    <p>Total $ <span id="total">0</span></p>

    I'd put your form into a table, then use character alignment to get all
    your numbers to line up.

    Cheers, Fred.

    Comment

    Working...