WillumMaguire
WillumMaguire

Reputation: 547

Multiple JavaScript functions not working correctly

Here's my code:

<script type="text/javascript" language="javascript">
function calc(){
    var a = prompt("Enter a number");
    var b = prompt("Enter another number");
    var x = +a;
    var y = +b;
    alert("The answer is " + (x+y));
}
function rect(type){
    var a = prompt("Enter length of rectangle");
    var b = prompt("Enter width of rectangle");
    var x = +a;
    var b = +b;
    if(type=="area"){
        alert("The area is " + (x*y);
    }
    else if(type=="perimeter"){
        alert("The perimeter is " + ( (2*x)+(2*y) );
    }
}
</script>

<head>
    <title>JavaScript Calculator</title>
</head>

<body>
    <button onclick="calc()">Calculator</button>
    <button onclick="rect('area')">Area of Rectangle</button>
    <button onclick="rect('perimeter')">Perimeter of Rectangle</button>
</body>

When I comment out the rect function, my code runs fine, it's just that the Calculator button is the only one that works. The other two buttons should be working fine with the rect function, but they aren't, and when I un-comment the rect function the Calculator button stops working as well. Why is this?

Upvotes: 0

Views: 2202

Answers (1)

jeremy
jeremy

Reputation: 10047

You're missing some parentheses

alert("The area is " + (x*y));
// and:
alert("The perimeter is " + ( (2*x)+(2*y) ));

Upvotes: 5

Related Questions