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 3 of 3
  1. #1
    New Coder
    Join Date
    Oct 2008
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Smile HELP! I am a newbee. Please be gentle.

    Hi I am just starting to learn javascript but having a few problems. At the bottom is the code for a simple mathamatical programme. I can't seem to make it work. I have tried everything I can think of, but I am obviously missing something. Please help.

    Here is the full code.

    <html>
    <head>
    <title>Test2</title>

    <script type="text/javascript">
    var num1=parseInt(document.getElementById("n1").value);
    var num2=parseInt(document.getElementById("n2").value);

    function calc(){
    var answer=0;

    if (document.getElementById("divide").value=="divide")
    answer=num1/num2;


    else
    answer=num1*num2;

    document.getElementById("ans").value=answer;
    }
    </script>


    </head>


    <body>


    <form id="form1" name="form1">

    Number1:
    <input type="text" Id="n1" Value="" /><br />

    Number2:
    <input type="text" Id="n2" Value="" /><br />


    Select:
    <select id="math" name="math" value="">

    <option id="select" name="select" value="">------ Select Activity ------</option>
    <option id="divide" name="divide" value="divide" onChange="calc();">Divide</option>
    <option id="multiply" name="divide" Value="multiply">Multiply</option>
    </select>


    <p>Answer: <input type="text" Id="ans" name="ans" readonly="readonly" Value="" /></p>
    <p><input type="reset" Id="reset" Value="Reset" /></p>

    </form>

    </body>

    </html>

  • #2
    New Coder
    Join Date
    Jun 2008
    Posts
    81
    Thanks
    2
    Thanked 16 Times in 16 Posts
    Hi,

    A few changes to the calc() function are needed:

    Code:
    function calc(){
      var num1 = parseInt(document.getElementById("n1").value);
      var num2 = parseInt(document.getElementById("n2").value);
      var answer=0;
    
      var sel = document.getElementById("math");
      if (sel.options[sel.selectedIndex].value =="divide")
        answer=num1/num2;
      else answer=num1*num2;
    
      document.getElementById("ans").value=answer;
    }
    Then move the function call into the <select> tag where it is actually needed:

    Code:
    <select id="math" name="math" value="" onchange="calc()">
    Now it should work.

  • #3
    New Coder
    Join Date
    Oct 2008
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thanks for that. It really helped.


  •  

    Posting Permissions

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