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

Thread: Adding elements

  1. #1
    Regular Coder
    Join Date
    Aug 2013
    Posts
    158
    Thanks
    23
    Thanked 0 Times in 0 Posts

    Adding elements

    Code:
    <input type="button" id="do10" value="Sub">
    <input type="text" id="cash_20" name="cash_20" readonly>
              <script>
    		  
    		  document.getElementById('do10').onclick = function() {
    document.getElementById('cash_20').value = document.getElementById('cash_9').value +  document.getElementById('cash_13').value + document.getElementById('cash_17').value +  document.getElementById('cash_18').value +  document.getElementById('cash_19').value +  document.getElementById('cash_3').value +  document.getElementById('cash_10').value +  document.getElementById('cash_6').value;
    };
    		  
    </script>
    Instead of adding the total it seems its just adding the numbers together, so instead of 12+13=25 its doing 12+13=1213.

    What am I doing wrong.

    And how would I add an elements with a number?

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    29,411
    Thanks
    85
    Thanked 4,907 Times in 4,868 Posts
    In JavaScript (and in Java and in several other languages), the + operator is used BOTH for adding numbers *AND* for concatenating two strings.

    Example:
    Code:
    var s = "Hello, " + "world"; // s is now "Hello, world"
    The .value property is *ALWAYS* a string

    So JavaScript sees you doing string + string and does string concatenation, not arithmetic.

    Many ways to fix this. The most common:
    Code:
    document.getElementById('cash_20').value = 
        Number(document.getElementById('cash_9').value) +  
        Number(document.getElementById('cash_13').value) + 
        ... etc. ...
    Convert the strings to numbers using the Number() function.
    Be yourself. No one else is as qualified.


  •  

    Posting Permissions

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