Talen Kylon
Talen Kylon

Reputation: 1958

Using javascript functions in HTML

I am creating a small webpage that will add two input fields together and place the result in another input field. This is what I have:

<html>
<head>
    <title>Calculator</title>

    <script type="text/javascript">
        function add(){
            var num1 = parseInt(document.calc.num1.value);
            var num2 = parseInt(document.calc.num2.value);
            var answer = (num1+num2);
            document.getElementById('res').value = answer;
        }
    </script>
</HEAD>

<BODY>
    <FORM NAME="calc">
        <INPUT TYPE ="button" NAME="add" Value="+" onClick="add()">
        <hr/>
        <INPUT TYPE ="text" NAME="num1" Value="">
        <INPUT TYPE ="text" NAME="num2" Value="">  
        <hr/>
        <INPUT TYPE ="text" ID="res" NAME="result" VALUE="">
    </FORM>
</BODY>
</HTML>

And I am getting the following error when I press the + button.

Uncaught TypeError: object is not a function 

Upvotes: 2

Views: 258

Answers (5)

Dissident Rage
Dissident Rage

Reputation: 2716

HTML

<p>
    <label for="field1">Field 1</label>
    <input type="number" id="field1"/>
</p>
<p>
    <label for="field2">Field 2</label>
    <input type="number" id="field2"/>
</p>
<p>
    <label for="total">Total</label>
    <input readonly type="number" id="total"/>
</p>
<p>
    <input type="button" id="calc" value="Calculate"/>
</p>

Javascript Goes in a script tag in head.

function sumFields(fields) {
    var total = 0;

    // goes through each field and adds them to the total
    for(var i=0,l=fields.length; i<l; i++)
        { total += parseInt(document.getElementById(fields[i]).value); }

    document.getElementById('total').value = total;
}

function calc_click() {
    // runs when the button is clicked
    sumFields(['field1','field2']);
}

// main function
function init() {
    // add button functionality
    document.getElementById('calc').addEventListener('click',calc_click,false);
}

// fires when the DOM is loaded
document.addEventListener('DOMContentLoaded',init,false);

Upvotes: 0

Antonio Romano
Antonio Romano

Reputation: 285

The problem is the name of the function "add()", change the name and you will see that it will works!

Upvotes: 0

Geordee Naliyath
Geordee Naliyath

Reputation: 1859

Try changing the function name from add to addNumbers or something like that.

Upvotes: 3

Vitor M. Barbosa
Vitor M. Barbosa

Reputation: 3646

onClick="add()"  

Switch this bit to

onclick="add()"

Upvotes: 0

invernomuto
invernomuto

Reputation: 10211

onclick is the right attribute to handle click

Upvotes: 0

Related Questions