I know this is probable a easy one for most of you...But this is my first Javascript. I am trying to write a code that will add two numbers entered by a user and calculate the sum. When I wrote the code inside the HTML it worked fine. But I have to use a .js file and call the function from there. And now my code does not work. Any guidance would be greatly appreciated. Here is the file

function addNumbers()
{                
                        var val1 = parseInt(document.getElementById("value1").value);
                        var val2 = parseInt(document.getElementById("value2").value);
                        var ansD = document.getElementById("answer");
                        ansD.value = val1 + val2;
}

ANd here is the HTML java3.html file

<?xml version="1.0" encoding="UTF-8" ?>    
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">


<!-- hello.html
A simple addition example of XHTML/JavaScript
-->

<html xmlns = "http://www.w3.org/1999/xhtml">


 <head>
        <title>Input tutorial</title>
        <script type="text"/javascript" src="numbers.js"></script>          
        
  </head>
  <body>
        value1 = <input type="text" id="value1" name="value1" value="1"/>
        value2 = <input type="text" id="value2" name="value2" value="2"/>
        <input type="button" name="Sumbit" value="Click here" onclick="javascript:addNumbers()"/>
        Answer = <input type="text" id="answer" name="answer" value=""/>
  </body>
</html>

Dani AI

Generated

A few focused checks and a small pattern to follow usually fixes this class of problem.

As pointed out, a malformed script tag prevents the external file from loading; as suggested, attaching the button handler from inside the JS (after the DOM is ready) avoids timing issues. The inputs showing "1" and "2" came from the HTML value attributes, so remove those if blanks are required. Another common cause is using a submit button which reloads the page (losing the calculated result) instead of a plain button.

Quick troubleshooting checklist:

  • Open DevTools: Console will show syntax errors or "addNumbers is not defined" and Network will show whether numbers.js returned 200 or 404.
  • Confirm the script tag is syntactically correct and the src path is relative to the HTML file location.
  • Use type="button" for the trigger (or preventDefault in the handler) so the page does not reload.
  • Prefer parseFloat/Number or parseInt(..., 10) and check for NaN before summing.

A robust pattern to keep all JS in the external file (attach after DOM ready) looks like this:

document.addEventListener('DOMContentLoaded', function () {
  var btn = document.getElementById('addBtn');
  btn.addEventListener('click', function () {
    var a = parseFloat(document.getElementById('value1').value);
    var b = parseFloat(document.getElementById('value2').value);
    var out = document.getElementById('answer');
    if (Number.isNaN(a) || Number.isNaN(b)) {
      out.value = 'enter numbers';
    } else {
      out.value = a + b;
    }
  }, false);
});

Extra notes: clear browser cache or force reload after updating numbers.js; saved files with a BOM or wrong MIME can cause silent failures in some setups; adding a couple of console.log statements inside the external file will quickly show whether it executed. These steps address the likely causes seen in the thread and make the solution more resilient.

Recommended Answers

All 4 Replies

syntax error

<script type="text"/javascript" src="numbers.js"></script>

Should be

<script type="text/javascript" src="numbers.js"></script>

Krako, Yes after I posted this I saw that error. But I fixed it and it still will not work. It pulls up the page and the boxes are there, but the number 1 and 2 are already in the box (there suppose to be blank) and even if i input new numbers and hit add it will not render a sum. ??????

Your code works fine with the function in <script></script> tags on the page.

If the code does not work with <script src=""></script> then it's because :

  • doesn't exist
  • exists but is in the wrong place
  • the function has not been cut/pasted into correctly.

Once you have got it working, then then you should really get ALL javascript into . To do this, you have to specify the button's behaviour in a different way.

This is going to take me longer to describe than to than to do, but here goes ....

  • Give the button an id.
  • Remove onclick="addNumbers()" from the button tag.
  • In the jacascript file add a window.onload handler. This will be of the general form :
    window.onload = function() {
      ........;//one or more statments
    };
  • In the window.onload handler, first use document.getElementById() to identify the button (you just gave it an id).
  • then, attach addNumbers as the button's onclick handler.

As this appears to be an assignment, I can't write it for you.

Airshow

ok js file is correct. But html file should be like this

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="numbers.js"></script>
</head>

<body>
<input type="text" id="value1" value="" />
<input type="text" id="value2" value="" />
<input type="submit" name="Submit" onclick="addNumbers()" />
<input type="text" id="answer" value="" />
</body>
</html>

I think the problem was in here

onclick="javascript:addNumbers()"/>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.