SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Jun 2006
    Posts
    12
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Javascript calculator help

    Hi everyone,

    I wonder if somebody would be kind enough to assist. I want to put up a simple javascript calculator where a user will enter two items, hit calculate and get a total in the third text box but my knowledge of javascript is severely limited.

    My simplified form (I left out calculate button):
    <input type="text"name="item1">
    <input type="text"name="item2">
    <input type="text"name="total" readonly>

    Whatever the user enters in text box item 1 must be multiplied by 0.5 = result 1
    Whatever the user enters in text box item 2 must be multiplied by 5 = result 2
    Text box total = result1 + result 2

    Any help will be greatly acknowledged

    Regards

    Anwar

  2. #2
    SitePoint Wizard
    Join Date
    Nov 2004
    Location
    Nelson BC
    Posts
    2,310
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    so you have calculate button:
    <button onclick="calculate();">Calculate</button>

    and the calculate function
    Code:
    function calculate() {
    // get values from textboxes
    var item1 = document.forms[0].elements["item1"].value;
    var item2 = document.forms[0].elements["item2"].value;
    
    // ensure valid input
    if( isNaN(parseFloat(item1)) || isNaN(parseFloat(item2)) ) {
    alert("bad input");
    return false;
    } else {
    item1 = parseFloat(item1);
    item2 = parseFloat(item2);
    }
    
    // do the calculation
    var total = item1 * 0.5 + item2 * 5;
    
    // write the result to the total textbox
    document.forms[0].elements["total"].value = total;
    
    }

  3. #3
    SitePoint Member
    Join Date
    Jun 2006
    Posts
    12
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    many many thanks jimfraser,

    it worked beautifully!

    Regards

    Anwar


Bookmarks

Posting Permissions

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