Thursday, June 6, 2024
 Popular · Latest · Hot · Upcoming
33
rated 0 times [  37] [ 4]  / answers: 1 / hits: 27645  / 11 Years ago, tue, may 7, 2013, 12:00:00

I need some help with a simple calculator I am doing with javascript.



The js code is as follows (my teacher want's me to use 4 functions, for each kind of operation):



<script>

function plus(a,b) {
return (a + b);
}

function minus(a,b) {
return (a - b);
}

function multiply(a,b) {
return (a * b);
}

function divide(a,b) {
return (a / b);
}

function calc() {

var x = document.getElementById(oper1).value;
var y = document.getElementById(operx).value;
var z = document.getElementById(oper2).value;
var w = document.getElementById(resul).value;

switch (y) {
case '0':
w = plus(x, z);
break;

case '1':
w = minus(x, z);
break;

case '2':
w = multiply(x, z);
break;

case '3':
w = divide(x, z);
break;

default:
w = Don't really know..;
}

}

</script>
<input type=text id=oper1 value=>

<select id=operx>
<option value=0>SUMAR</option>
<option value=1>RESTAR</option>
<option value=2>MULTIPLICAR</option>
<option value=3>DIVIDIR</option>
</select>

<input type=text id=oper2 value=>
<input type=button onClick=calc(); value==>
<input type=text id=resul value=>


My code isn't working, in fact is not responding anything and I don't see any errors so I can debug... could anyone tell me if you see my mistake here? I've tried hundreds of combinations but without having an debug console or something.


More From » html

 Answers
-4

JavaScript does not use pointers in the way you intend to use them. You have to explicitly write back your result to the output field:



function calc(){
// most of your stuff
// just replace the var w = document ... line with just
var w;

// your other code

document.getElementById(resul).value = w;
}


Furthermore, you should parse the input values into a number using either parseInt() or parseFloat(). If you don't JavaScript will treat the input values as strings and then interprets + as string concatenation, for example.



Example Fiddle


[#78384] Monday, May 6, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rossj

Total Points: 606
Total Questions: 100
Total Answers: 116

Location: Dominican Republic
Member since Sun, Sep 4, 2022
2 Years ago
;