JS implements a simple calculator
Use JS to complete a simple calculator function. After entering integers in the two input boxes, click the third input box to give the addition, subtraction, multiplication and division of the two integers. The effect is as follows:
Step 1: create the build operation function count ().
Step 2: get the values in the two input boxes and the values in the selection box.
Tip: document.getElementById (id name). Value gets or sets the value of the id name.
Step 3: get the value selected by the drop-down box to change the algorithm of addition, subtraction, multiplication and division.
Tip: use switch to judge the algorithm.
Step 4: call the created function through the = button to get the result.
Note: use the parseInt () function to parse a string and return an integer.
Code:
12 3 4 event 56 function count () {7 var a = document.getElementById ("txt1"). Value; 8 var b = document.getElementById ("txt2"). Value; 9 / / get the value of the first input box 10 / / get the value of the second input box 11 / / get the value of the selection box 12 var c = document.getElementById ("select"). Value;13 a = parseFloat (a); 14 b = parseFloat (b) 15 / / get the value selected through the drop-down box to change the algorithm of addition, subtraction, multiplication and division 16 / / set the value of the result input box 17 switch (c) {18 case "+": 19 document.getElementById ("fruit") .value = parseInt (a) + parseInt (b); 20 break;21 case "-": 22 document.getElementById ("fruit") .value = parseInt (a)-parseInt (b); 23 break 24 case "*": 25 ocument.getElementById ("fruit") .value = parseInt (a) * parseInt (b); 26 break;27 case "/": 28 document.getElementById ("fruit") .value = parseInt (a) / parseInt (b); 29 break 30} 31} 32 33 34 35 36 37 + 38-39 * 40 / 41 42 43 44 45 46