Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Feb 2008
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Javascript Math Onclick Help

    I'm new to javascript and heres my question.

    I have a script that adds values to a total every time a checkbox is clicked.
    Code:
        <script type="text/javascript">
        function calculate() {
        var elems = document.forms['order'].elements;
        var total = 0;
        for(var i=0;i<elems.length;i++) {
        if (elems[i].checked) {total += +(elems[i].value);}
        }
        elems['total'].value = total;
        }
        </script>
    However I want to add the following functionality and I'm lost. When the user selects from a dropdown, I want the total to be multiplied by a different value assigned to each option in the drop down.

    Thanks in advance for your help.

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,730
    Thanks
    202
    Thanked 2,507 Times in 2,485 Posts
    Something like this:-

    Code:
    <form name = "order">
    <select name = "s" id = "s" onchange = "getValue()">
    <option value = "0">Select an option
    <option value = "1">One
    <option value = "2">Two
    <option value = "3">Three
    </select>
    </form>
    
    
    <script type = "text/javascript">
    
    var mult = 0;
    function getValue() {
    mult = document.order.s.value;
    }
    
    function calculate() {
    if (mult == 0) {
    alert ("You must select an option value");
    return false;
    }
    var elems = document.forms['order'].elements;
    var total = 0;
    for(var i=0;i<elems.length;i++) {
    if (elems[i].checked) {total += +(elems[i].value);}
    }
    elems['total'].value = total;
    total = total * mult;
    }
    
    </script>

    BTW, the time to say "thanks" is afterwards, not beforehand which gives the impression that you take other people's unpaid assistance for granted. Or as British politician Neil Kinnock put it, "Don't belch before you have had the meal." Prefer to use "please" beforehand and if you find a response helpful then you can use the "Thank User For This Post" button.
    Last edited by Philip M; 09-02-2008 at 08:16 AM.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •