Results 1 to 5 of 5

Thread: calculate all elements in array call with button

Hybrid View

  1. #1
    Join Date
    Sep 2012

    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

    <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");
    x.innerHTML = number.join('<br/>');

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


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

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

  2. #2
    Join Date
    Sep 2007
    I am trying

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

  3. #3
    Join Date
    Sep 2012
    hey thanks this works

  4. #4
    Join Date
    Jul 2008
    urbana, il
    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)
    Create, Share, and Debug HTML pages and snippets with a cool new web app I helped create: pagedemos.com

  5. #5
    Join Date
    Sep 2012
    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