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 4 of 4
  1. #1
    New to the CF scene
    Join Date
    Jul 2012
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Javascript numbers help

    Hi I am new to learning Javascript. I want an alert to add two numbers from 2 text boxes together. What i get is 1 + 2 = 12.

    Here is my code:
    JavaScript:

    function sum(){
    var no1 =document.getElementById('no1').value;

    var no2 =document.getElementById('no2').value;

    var total=no1+no2;

    alert (total)
    }

    HTML
    <p>Number 1 <input type="text" id="no1"></p>

    <p>Number 2 <input type="text" id="no2">
    <input type="button" value="add" onclick="sum()"></p>

    Please help

  • #2
    Regular Coder
    Join Date
    Apr 2012
    Location
    St. Louis, MO
    Posts
    985
    Thanks
    7
    Thanked 101 Times in 101 Posts
    In JavaScript, "+" is concatenation unless you specify otherwise.

    var total = parseFloat(no1) + parseFloat(no2);
    ^_^

    If anyone knows of a website that can offer ColdFusion help that isn't controlled by neurotic, pedantic jerks* (stackoverflow.com), please PM me with a link.
    *
    The neurotic, pedantic jerks are not the owners; just the people who are in control of the "popularity contest".

  • #3
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,156
    Thanks
    203
    Thanked 2,548 Times in 2,526 Posts
    var no1 =document.getElementById('no1').value;

    Do not use the same name for a Javascript variable and an HTML element. It will in fact work here, but is very dangerous.

    All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #4
    Regular Coder
    Join Date
    Apr 2012
    Location
    St. Louis, MO
    Posts
    985
    Thanks
    7
    Thanked 101 Times in 101 Posts
    Och.. I was in a hurry and forgot the string delimiters! Tnx, Philip.
    ^_^

    If anyone knows of a website that can offer ColdFusion help that isn't controlled by neurotic, pedantic jerks* (stackoverflow.com), please PM me with a link.
    *
    The neurotic, pedantic jerks are not the owners; just the people who are in control of the "popularity contest".


  •  

    Posting Permissions

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