Welcome to Dream.In.Code
Getting Help is Easy!

Join 136,254 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 2,226 people online right now. Registration is fast and FREE... Join Now!




How can I add number values from dropbox to total?

 
Reply to this topicStart new topic

How can I add number values from dropbox to total?

kr580
11 Oct, 2008 - 03:52 PM
Post #1

New D.I.C Head
*

Joined: 11 Oct, 2008
Posts: 3

I'm trying to create a form for a friend of mine and need some help with javascript. I'm new to javascript so it isn't going very smoothly.

What I'm trying to do now is have a dropbox with several packages for sale which each have a number value (price) which, when selected, will send that number to the Subtotal box and calculate the rest automatically. I need this to update when you change the dropbox option.


Here's what I've come up with. As you can tell I'm a bit (a lot) lost. The dropdown box and checkboxes add to the Subtotal fine but there's a couple problems.

1. Subtotal value does not trigger the Tax and Total auto-calculation.
2. onMouseDown for dropbox options just tallies the price each time you click an option, it doesn't replace with it's single value.

CODE



<html>
<head>
<title>Untitled Document</title>
<script LANGUAGE="JavaScript">

<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->
<!-- Original:  Paul DeBrino -->
<!-- Web Site:   http://infinity-rd.com -->
<!-- Begin
    function CheckChoice(whichbox)
    {
        with (whichbox.form)
        {
            //Handle differently, depending on type of input box.
            if (whichbox.type == "select")
            {
                //First, back out the prior radio selection's price from the total:
                hiddentotal.value = eval(hiddentotal.value) - eval(hiddenpriorselect.value);
                //Then, save the current radio selection's price:
                hiddenpriorselect.value = eval(whichbox.price);
                //Now, apply the current radio selection's price to the total:
                hiddentotal.value = eval(hiddentotal.value) + eval(whichbox.price);
            }
            else
            {
                //If box was checked, accumulate the checkbox value as the form total,
                //Otherwise, reduce the form total by the checkbox value:
                if (whichbox.checked == false)
                    { hiddentotal.value = eval(hiddentotal.value) - eval(whichbox.value); }
                else     { hiddentotal.value = eval(hiddentotal.value) + eval(whichbox.value); }
            }

            //Ensure the total never goes negative (some browsers allow radiobutton to be deselected):
            if (hiddentotal.value < 0)
                {
                InitForm();
                }

            //Now, return with formatted total:
            return(formatCurrency(hiddentotal.value));
        }
    }

    //Define function to format a value as currency:
    function formatCurrency(num)
    {
       // Courtesy of http://www7.brinkster.com/cyanide7/
        num = num.toString().replace(/\$|\,/g,'');
        if(isNaN(num))
           num = "0";
        sign = (num == (num = Math.abs(num)));
        num = Math.floor(num*100+0.50000000001);
        cents = num%100;
        num = Math.floor(num/100).toString();
        if(cents<10)
            cents = "0" + cents;
        for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
            num = num.substring(0,num.length-(4*i+3))+','+
                  num.substring(num.length-(4*i+3));
          return (((sign)?'':'-') + '' + num + '.' + cents);
    }

    //Define function to init the form on reload:
    function InitForm()
        {
        //Reset the displayed total on form:
        document.form1.Subtotal.value='0';
        document.form1.hiddentotal.value=0;
        document.form1.hiddenpriorradio.value=0;

        //Set all checkboxes and radio buttons on form-1 to unchecked:
        for (xx=0; xx < document.form1.elements.length; xx++)
        {
           if (document.form1.elements[xx].type == 'checkbox' | document.form1.elements[xx].type == 'radio')
            {
            document.form1.elements[xx].checked = false;
            }
        }
    }

function totalprice()
{
a = document.form1.Subtotal.value

b = (Math.round((a * 0.0825) / .01) * .01)
c = (a * 1) + (b * 1)


document.form1.Tax.value = b
document.form1.Total.value = c
}
</script>
</head>

<body onLoad="InitForm();" onreset="InitForm();">
<table width="220" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td><form method="post" name="form1">
      <div align="right">
        <select name="Type of shoot">
        <option name="Please Choose" value="Please Choose" selected>Please Choose</option>
        <option name="CD Coverage 1.5 hours" value=525 onMouseDown="form1.Subtotal.value=CheckChoice(this);">Option 1</option>
        <option name="CD Coverage 3 hours" value=990 onMouseDown="form1.Subtotal.value=CheckChoice(this);">Option 2</option>
        <option name="CD Coverage 6 hours" value=1650 onMouseDown="form1.Subtotal.value=CheckChoice(this);">Option 3</option>
        <option name="CD Coverage 9 hours" value=2500 onMouseDown="form1.Subtotal.value=CheckChoice(this);">Option 4</option>
        </select><br><br>
        Addon #1 - $20 <input type="checkbox" name="Addon1" value=20 onclick="form1.Subtotal.value=CheckChoice(this);"><br>
        Addon #2 - $50 <input type="checkbox" name="Addon2" value=50 onclick="form1.Subtotal.value=CheckChoice(this);"><br>
        Addon #3 - $70 <input type="checkbox" name="Addon2" value=70 onclick="form1.Subtotal.value=CheckChoice(this);">
<br>
<br>
<br>

        
        <strong><u>Price</u></strong><br />
        <input type="hidden" name="hiddentotal" value=0>
        <input type="hidden" name="hiddenpriorradio" value=0>
        $<input type="text" name="Subtotal" size="10" readonly onFocus="this.blur();" onChange="totalprice();">
        <br />
        Sales Tax (8.75%): $<input name="Tax" size="10" readonly="true" />
        <br />
        Total: $<input name="Total" size="10" readonly="true" />
        <br /></div><input type="hidden" name="hiddentotal" value=0>
            <input type="hidden" name="hiddenpriorradio" value=0>
        </form>
    </td>
  </tr>
</table>
</body>
</html>


Any help at all is much appreciated.

Thank You - Kevin
User is offlineProfile CardPM
+Quote Post

William_Wilson
RE: How Can I Add Number Values From Dropbox To Total?
11 Oct, 2008 - 05:22 PM
Post #2

lost in compilation
Group Icon

Joined: 23 Dec, 2005
Posts: 3,984



Thanked: 16 times
Dream Kudos: 3275
Expert In: Java, C, Javascript

My Contributions
The tax needs some work to only display 2 decimals, but I think that's something i'll leave for you. I added the totalPrice call to the end of each subtotal update, which will update the other fields. I took the liberty of fixing the issues with your totalprice method (figured you wouldn't mind tongue.gif) The value is a string and often contains a comma, so they need to be removed and converted to an integer, but i think the a = line is pretty self explanatory. Hope this helps smile.gif
CODE

<html>
<head>
<title>Untitled Document</title>
<script LANGUAGE="JavaScript">

<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->
<!-- Original:  Paul DeBrino -->
<!-- Web Site:   http://infinity-rd.com -->
<!-- Begin
    function CheckChoice(whichbox)
    {
        with (whichbox.form)
        {
            //Handle differently, depending on type of input box.
            if (whichbox.type == "select")
            {
                //First, back out the prior radio selection's price from the total:
                hiddentotal.value = eval(hiddentotal.value) - eval(hiddenpriorselect.value);
                //Then, save the current radio selection's price:
                hiddenpriorselect.value = eval(whichbox.price);
                //Now, apply the current radio selection's price to the total:
                hiddentotal.value = eval(hiddentotal.value) + eval(whichbox.price);
            }
            else
            {
                //If box was checked, accumulate the checkbox value as the form total,
                //Otherwise, reduce the form total by the checkbox value:
                if (whichbox.checked == false)
                    { hiddentotal.value = eval(hiddentotal.value) - eval(whichbox.value); }
                else     { hiddentotal.value = eval(hiddentotal.value) + eval(whichbox.value); }
            }

            //Ensure the total never goes negative (some browsers allow radiobutton to be deselected):
            if (hiddentotal.value < 0)
                {
                InitForm();
                }

            //Now, return with formatted total:
            return(formatCurrency(hiddentotal.value));
        }
    }

    //Define function to format a value as currency:
    function formatCurrency(num)
    {
       // Courtesy of http://www7.brinkster.com/cyanide7/
        num = num.toString().replace(/\$|\,/g,'');
        if(isNaN(num))
           num = "0";
        sign = (num == (num = Math.abs(num)));
        num = Math.floor(num*100+0.50000000001);
        cents = num%100;
        num = Math.floor(num/100).toString();
        if(cents<10)
            cents = "0" + cents;
        for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
            num = num.substring(0,num.length-(4*i+3))+','+
                  num.substring(num.length-(4*i+3));
          return (((sign)?'':'-') + '' + num + '.' + cents);
    }

    //Define function to init the form on reload:
    function InitForm()
        {
        //Reset the displayed total on form:
        document.form1.Subtotal.value='0';
        document.form1.hiddentotal.value=0;
        document.form1.hiddenpriorradio.value=0;

        //Set all checkboxes and radio buttons on form-1 to unchecked:
        for (xx=0; xx < document.form1.elements.length; xx++)
        {
           if (document.form1.elements[xx].type == 'checkbox' | document.form1.elements[xx].type == 'radio')
            {
            document.form1.elements[xx].checked = false;
            }
        }
    }

function totalprice()
{
a = parseInt(document.form1.Subtotal.value.replace(/,/,""));

b = (Math.round((a * 0.0825) / .01) * .01);
c = (a * 1) + (b * 1);


document.form1.Tax.value = b;
document.form1.Total.value = c;
}
</script>
</head>

<body onLoad="InitForm();" onreset="InitForm();">
<table width="220" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td><form method="post" name="form1">
      <div align="right">
        <select name="Type of shoot">
        <option name="Please Choose" value="Please Choose" selected>Please Choose</option>
        <option name="CD Coverage 1.5 hours" value=525 onMouseDown="form1.Subtotal.value=CheckChoice(this);totalprice();">Option 1</option>
        <option name="CD Coverage 3 hours" value=990 onMouseDown="form1.Subtotal.value=CheckChoice(this);totalprice();">Option 3</option>
        <option name="CD Coverage 9 hours" value=2500 onMouseDown="form1.Subtotal.value=CheckChoice(this);totalprice();">Option 4</option>
        </select><br><br>
        Addon #1 - $20 <input type="checkbox" name="Addon1" value=20 onclick="form1.Subtotal.value=CheckChoice(this);totalprice();"><br>
        Addon #2 - $50 <input type="checkbox" name="Addon2" value=50 onclick="form1.Subtotal.value=CheckChoice(this);totalprice();"><br>
        Addon #3 - $70 <input type="checkbox" name="Addon2" value=70 onclick="form1.Subtotal.value=CheckChoice(this);totalprice();">
<br>
<br>
<br>

        
        <strong><u>Price</u></strong><br />
        <input type="hidden" name="hiddentotal" value=0>
        <input type="hidden" name="hiddenpriorradio" value=0>
        $<input type="text" name="Subtotal" size="10" readonly onFocus="this.blur();">
        <br />
        Sales Tax (8.75%): $<input name="Tax" size="10" readonly="true" />
        <br />
        Total: $<input name="Total" size="10" readonly="true" />
        <br /></div><input type="hidden" name="hiddentotal" value=0>
            <input type="hidden" name="hiddenpriorradio" value=0>
        </form>
    </td>
  </tr>
</table>
</body>
</html>

You were really close, it isn't that bad considering you're new to javascript. I would suggest for future scripts that you use functions to set all values and not set them directly within the onMouseDown, or other similar calls.

This post has been edited by William_Wilson: 11 Oct, 2008 - 05:23 PM
User is offlineProfile CardPM
+Quote Post

kr580
RE: How Can I Add Number Values From Dropbox To Total?
11 Oct, 2008 - 06:11 PM
Post #3

New D.I.C Head
*

Joined: 11 Oct, 2008
Posts: 3

Oh wow, you're a saint. Thank you so much!

One thing though, is there any simple way to make it so the subtotal just takes the selected total from the dropbox and not tally up the values if you switch the option? I can't figure out how to make that work for the life of me. sad.gif

Again any help is much appreciated!

Thanks - Kevin
User is offlineProfile CardPM
+Quote Post

William_Wilson
RE: How Can I Add Number Values From Dropbox To Total?
12 Oct, 2008 - 04:10 AM
Post #4

lost in compilation
Group Icon

Joined: 23 Dec, 2005
Posts: 3,984



Thanked: 16 times
Dream Kudos: 3275
Expert In: Java, C, Javascript

My Contributions
your code inside the if statement: if (whichbox.type == "select") never gets called, there is no type attribute on the option tags, so you will either need to add it, or come up with a better if condition.

also once your if statement works, you have a complicated setup of additions and subtractions, when all you seem to want is: hiddentotal.value = whichbox.value;, in which case the hidden value really isn't necessary, but it's your choice. Personally I would split up the check boxes and the drop down list to call separate functions. It will make your life much easier.
User is offlineProfile CardPM
+Quote Post

kr580
RE: How Can I Add Number Values From Dropbox To Total?
12 Oct, 2008 - 12:27 PM
Post #5

New D.I.C Head
*

Joined: 11 Oct, 2008
Posts: 3

Thank you so much for the help. It looks like I have a lot more learning to do. smile.gif

- Kevin
User is offlineProfile CardPM
+Quote Post

JMRKER
RE: How Can I Add Number Values From Dropbox To Total?
25 Oct, 2008 - 10:00 AM
Post #6

New D.I.C Head
*

Joined: 25 Oct, 2008
Posts: 44



Thanked: 3 times
My Contributions
This is a different approach to what I believe you are trying to do.
Substitute your own descriptions and costs in the script.
I have not included a tax and totals calculation, but it should be fairly easy to add.
If you need to total all the group selections, then additional mods would be needed
but if you just want to summarize the particuar group (Game, Food, or Car in this example)
it should fill the need with additional modifications.

Post back if you have questions about further modifications.
CODE

<html>
<head>
<title>Multiple CBox Prices</title>
<script type="text/javascript">
function UpdateGroups(Group) {
  var elem = document.getElementById(Group);
  var GN = elem.selectedIndex;                                  // alert(elem.id+'\n'+GN);
  var ID = elem.options[GN].value;                                // alert(ID);
  for (i=0; i<elem.options.length; i++) {
    document.getElementById(elem.options[i].value).style.display = 'none';      
  }
  document.getElementById(ID).style.display = 'block';            // alert(elem.id+'\n'+ID);
  UpdateCost(ID);
}
function UpdateCost(Category) {
  var sum = 0;
  var gn, elem;
  Cnt = document.getElementById(Category).getElementsByTagName('input').length;
  for (i=0; i<Cnt; i++) {
    gn = Category+i;
    elem = document.getElementById(gn);        // alert(elem.id+'\n'+gn);
    if (elem.checked == true) { sum += Number(elem.value); }
  }
  document.getElementById('totalcost').value = sum.toFixed(2);
}
</script>
</head>
<body>

<select id="Groups" onchange="UpdateGroups(this.id)">
<option value="Blank">Select</option>
<option value="Game">Games</option>
<option value="Food">Foods</option>
<option value="Car">Cars</option>
</select>
<div id="Blank" style="display:block"></div>

<div id="Game" style="display:none">
<input type="checkbox" id='Game0' value="9.99"  onclick="UpdateCost('Game')">Game 1 ( 9.99)<br>
<input type="checkbox" id='Game1' value="19.99" onclick="UpdateCost('Game')">Game 2 (19.99)<br>
<input type="checkbox" id='Game2' value="27.50" onclick="UpdateCost('Game')">Game 3 (27.50)<br>
<input type="checkbox" id='Game3' value="45.65" onclick="UpdateCost('Game')">Game 4 (45.65)<br>
<input type="checkbox" id='Game4' value="87.20" onclick="UpdateCost('Game')">Game 5 (87.20)<br>
</div>

<div id="Food" style="display:none">
<input type="checkbox" id='Food0' value="0.99" onclick="UpdateCost('Food')">Food 1 (0.99)<br>
<input type="checkbox" id='Food1' value="1.99" onclick="UpdateCost('Food')">Food 2 (1.99)<br>
<input type="checkbox" id='Food2' value="2.99" onclick="UpdateCost('Food')">Food 3 (2.99)<br>
<input type="checkbox" id='Food3' value="3.99" onclick="UpdateCost('Food')">Food 4 (3.99)<br>
<input type="checkbox" id='Food4' value="4.99" onclick="UpdateCost('Food')">Food 5 (4.99)<br>
<input type="checkbox" id='Food5' value="5.99" onclick="UpdateCost('Food')">Food 6 (5.99)<br>
<input type="checkbox" id='Food6' value="6.99" onclick="UpdateCost('Food')">Food 7 (6.99)<br>
<input type="checkbox" id='Food7' value="7.99" onclick="UpdateCost('Food')">Food 8 (7.99)<br>
<input type="checkbox" id='Food8' value="8.99" onclick="UpdateCost('Food')">Food 9 (8.99)<br>
<input type="checkbox" id='Food9' value="9.99" onclick="UpdateCost('Food')">Food 10 (9.99)<br>
</div>

<div id="Car" style="display:none">
<input type="checkbox" id='Car0' value="12999" onclick="UpdateCost('Car')">Car 1 (12999)<br>
<input type="checkbox" id='Car1' value="15999" onclick="UpdateCost('Car')">Car 2 (15999)<br>
<input type="checkbox" id='Car2' value="19999" onclick="UpdateCost('Car')">Car 3 (19999)<br>
<input type="checkbox" id='Car3' value="21000" onclick="UpdateCost('Car')">Car 4 (21000)<br>
<input type="checkbox" id='Car4' value="23000" onclick="UpdateCost('Car')">Car 5 (23000)<br>
<input type="checkbox" id='Car5' value="25000" onclick="UpdateCost('Car')">Car 6 (25000)<br>
<input type="checkbox" id='Car6' value="30000" onclick="UpdateCost('Car')">Car 7 (30000)<br>
</div>

<input type="text" id="totalcost" value="">

</body>
</html>


User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 12/2/08 04:21AM

Live Help!

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month