+ 2

Something i made on my own

<script type="text/javascript"> var a=document.getElementById("demo"); var b=document.getElementById("demo2"); function add(){ return alert(a+b); } function sub(){ return alert(a-b); } function mul(){ return alert(a*b); } function div(){ return alert(a/b); } Guys i was trying to make a calculator with java script and Html and i assigned a onclick thing but it returns the Nan error when i click the button what should i do to fix it

9th Apr 2020, 4:56 PM
Immortal Soul
Immortal Soul - avatar
4 Antworten
+ 4
Immortal Soul , Nice efforts 👏. Just a few things you did wrong 1. document .getElementById('demo1') will return Element object representing element whose id is `demo1`. If your element is a input , textarea you can use `value` attribute to retrieve it's value given as input. Also make sure you convert this value to Number type , by default it's a String. use parseInt() method. a = parseInt( document .getElementById('demo1').value ); Same applies to 'demo2'. 2.Trying to convert a value to Number that is not representable as Number will give result NaN. Number('wrongString') //NaN Number('23') //23 This is reason why you are getting NaN. Performing arithmetic operations on HTMLElement objects produces NaN. 3. In your functions add, sub, mul and div you are performing an unnecessary operation. returning result of alert(). alert itself returns `undefined` so better remove all `return`s. Note that even if you keep `return` it'll work just fine but you don't need to return result so don't use.
9th Apr 2020, 5:16 PM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 1
Ok
9th Apr 2020, 5:28 PM
Immortal Soul
Immortal Soul - avatar
+ 1
Thanks
9th Apr 2020, 5:28 PM
Immortal Soul
Immortal Soul - avatar
+ 1
Um getting confused on how to use the parseint method can u help??
9th Apr 2020, 7:05 PM
Immortal Soul
Immortal Soul - avatar