0

I tried to make this simple JS calculator following a tutorial I found but it doesn't seem to be working at all. When I press one of the buttons nothing happens. I probably made a really stupid mistake so I'm sorry if I'm wasting your time. I've troubleshooted it but I can't find a solution.

Correction: It works now!

var a,b,result;
    function setValues()
    {
    	a = Number(document.getElementById("a").value);
    	b = Number(document.getElementById("b").value);
    }
    
    function sum()
    {
    	setValues();
    	result = a+b;
    	alert("The sum is equal to"+result);
    }
    
    function rest()
    {
    	setValues();
    	result = a-b;
    	alert("The rest is equal to"+result);
    }
    
    function mult()
    {
    	setValues();
    	result = a*b;
    	alert("The mult is equal to"+result);
    }
    
    function div()
    {
    	setValues();
    	result = a/b;
    	alert("The div is equal to"+result);
    }
<div>
  <input id="a" type="text">
  <input id="b" type="text">
  <input type="button" onclick="sum()" value="sum"/>
  <input type="button" onclick="rest()" value="rest"/>
  <input type="button" onclick="mult()" value="multiply"/>
  <input type="button" onclick="div()" value="divide"/>

</div>

2
  • what errors are you seeing? anything in your console? is anything being alerted? (n.b use parseInt() rather then Number()) Commented Jan 5, 2015 at 11:21
  • I've voted to close this as it's a simple typographical error. getElementByID should be getElementById. Commented Jan 5, 2015 at 11:24

2 Answers 2

1

You can check that your console (F12) is throwing error.

Change

document.getElementByID("a").value

to

document.getElementById("a").value

JavaScript is Case-Sensitive. So that's why js does not find getElementByID

Sign up to request clarification or add additional context in comments.

Comments

0

Typo?

a = Number(document.getElementByID("a").value);
b = Number(document.getElementByID("b").value);

Try:

a = Number(document.getElementById("a").value);
b = Number(document.getElementById("b").value);

3 Comments

I create a fiddle for same, jsfiddle.net/ucrjp9yn, made the "ID" to "Id" change, but it's still not working, are you sure the problem is that only?
@RohitAggarwal yes. The problem in your case is jsfiddle itself. Copy and Paste it into a local file and fire up your favourite browser and it should work.
Yes, run the snippet above and try for yourself if you want!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.