www.webdeveloper.com
Results 1 to 5 of 5

Thread: calculate all elements in array call with button

  1. #1
    Join Date
    Sep 2012
    Posts
    6

    calculate all elements in array call with button

    trying to sum all elements in the array "number" have in shown in the form "output" when user clicks on the button, im using a example i found on the net but cant seem to make it owrk or any other example if any can pls help me to understand thanks

    [COLOR="#EE82EE"]<body>
    <script type="text/javascript">
    var number = [];

    Array.prototype.sum = function()
    {
    for (var i = 0, L = this.length, sum = 0; i < L; sum += this[i++]);
    return sum(document.getElementById("output").value);
    }


    function myFunction() {
    var x = document.getElementById("box");
    number.push(document.getElementById("input").value);
    x.innerHTML = number.join('<br/>');
    }

    function myReset() {
    number=[]
    number.splice(0);
    var x = document.getElementById("box");
    x.innerHTML = "";
    x.innerHTML = number.join('<br/>');
    }

    </script>

    <form>
    <input id="input" type=text>
    <input type=button onclick="myFunction()" value="Add to list"/>
    </form>

    <div id="box" style="border:1px solid black;width:150px;height:150px;overflow:scroll">
    </div>
    <form>
    <input type=button onclick="number.sum()" value="Calculate"/>
    <input type=button onclick="myReset()" value="Reset" /> </br></br>
    <b>Total(sum):</b></br>
    <input id="output" type=text>
    </form>
    </body>

  2. #2
    Join Date
    Sep 2007
    Posts
    301
    I am trying

    for (var i = 0, L = this.length, sum = 0; i < L; sum += Number(this[i++] ));
    return document.getElementById("output").value = sum;
    İyiliği emret. Kötülükten alıkoy. (31/16)

    hasbunallahuVeNimelVekil++

  3. #3
    Join Date
    Jul 2008
    Location
    urbana, il
    Posts
    2,787
    don't hard-code math and dom handles together.
    try to use pure functions to do your data processing:

    [1,2,3,4].reduce(function sum(a,b){return a+b;});

    you need to turn the string .value of the input into a number that adds (strings concat)

  4. #4
    Join Date
    Sep 2012
    Posts
    6
    hey thanks this works

  5. #5
    Join Date
    Sep 2012
    Posts
    6
    Thanks you for your reply a little over my head i will study the DOM tutorials as i havent done them in my course as of yet thanks

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

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



Recent Articles