CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Oct 2010
    Posts
    1

    calculating the total value of numbers in a textarea

    I have some code that gives me the sum of numbers in a textarea (see below), but it only works on the first line and if there are more then one spaces between numbers it gives an error.

    I basically want it to give me the sum of all numbers in the textare irrespective of spaces between them or lines separating them.

    Any help will be apreciated



    </html>
    <head>
    <meta http-equiv='Content-type' content='text/html;charset=UTF-8'>
    <title>Calc Numbers</title>
    <script type='text/javascript'>
    function calc() {
    // calc() is designed to sum numbers entered in an input field
    var t = document.getElementById("num").value; // the numbers entered
    var numbers = new Array();
    numbers = t.split(' '); // the numbers extracted from the string
    var sum = 0; // variable to hold the sum of the numbers
    var num = ''; // string to hold a list of the numbers
    if (numbers.length == 1) { num = '0'; } // to add single number to
    for (i = 0; i < numbers.length; i++) {
    sum = sum + eval(numbers[i]); // add this number
    if (i == numbers.length - 1) { num = num + " and ";} // last number?
    else { if (i > 0) { num = num + ", "} } // otherwise if not 1st, join with ,
    num = num + numbers[i]; // and add the number to the list
    }
    // create the text to display with the result
    result = "<p>The sum of the numbers " + num + " is " + sum +"<"+"/p>";
    // find the placeholder for displaying the result
    var resElement = document.getElementById("res");
    // display the result
    resElement.innerHTML = result;
    }
    </script>
    </head>
    <body>
    <h1>Calc Numbers</h1>
    <p>Enter some numbers separated by spaces:</p>


    <textarea id='num' onclick="this.value=''" onchange='calc()' cols = 65 rows = 5 wrap="PHYSICAL"></textarea>
    <!-- provide a dummy button - encourage user to leave input tag -->
    <input type="button" value="Calc">
    <!-- the following div id='res' provides a placeholder
    that calc() can use to display the result -->
    <div id='res'></div>
    </body>
    </html>

  2. #2
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: calculating the total value of numbers in a textarea

    This is a Java forum not a javascript forum. Try posting on the client side scripting forum.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured