-4

i am trying to make a maths engine with JavaScript and HTML.
Here is (https://i.stack.imgur.com/NCEa4.jpg)

The alert from the js alert() function works but the output from it is wrong:
'HTMLObject'

user3671292
  • 83
  • 1
  • 6
  • 2
    Please next time post your code as a String, not an Image :) – dfsq May 24 '14 at 08:38
  • Use jsfiddle.com to post your code.Will be easy for others to give you a working example. – Madhurendra Sachan May 24 '14 at 08:40
  • The code in the image has a syntax error, such that won't do anything at useful, not even output "11". *Read the error console*. When you *do* ask a question on SO 1) include the *actual* code; and 2) report the problem (including the title) correctly. – user2864740 May 24 '14 at 08:44
  • The title doesn't seem to have anything to do with your problem/the rest of the question. – Felix Kling May 24 '14 at 08:46

5 Answers5

0

Use 'parseInt()' function to convert those values to integers first and then add the values.

halkujabra
  • 2,844
  • 3
  • 25
  • 35
0

Value of the input field is always a string. So when you use + operator with two strings it concatenates them. If you want to add two numbers you need first to convert strings to numbers. There are multiple ways to do it, for example:

var plus = parseInt(one) + parseInt(two);

Or you can use Number(one), or another unary + operator: +one + +two, but this might look confusing.

dfsq
  • 191,768
  • 25
  • 236
  • 258
0

make your variable plus like this:

var plus = parseInt(one) + parseInt(two);
droymanz
  • 343
  • 8
  • 18
0

You need to enclose your function code in curly braces { & }.

So Use:

function Maths(){
var one=document.getElementById("fid").value;
var two=document.getElementById("sid").value;
var plus=Math.parseInt(one)+Math.parseInt(two);
alert(plus);
}

Also use parseInt() to make data type conversion to convert to int in JavaScript.

Hope it'll help you. Cheers :)!!

Vedant Terkar
  • 4,553
  • 8
  • 36
  • 62
0

Will be better if you use second argument in parseInt for be sure that value will be in decimal system.

function Maths() {
    var one = document.getElementById("fid").value,
        two = document.getElementById("sid").value,
        plus = Math.parseInt(one, 10) + Math.parseInt(two, 10);

    alert(plus);
}
Eugene Obrezkov
  • 2,910
  • 2
  • 17
  • 34