简体   繁体   中英

Simple calculator using JavaScript

I'm trying to create a simple JavaScript calculator but its not working as expected.

I tried but I'm getting correct results. Below is my code. please let me know what I'm doing wrong here

Below is the HTML and JavaScript code.

Note : HTML structure cannot be changed.

 function update(value) { //Type the code here. document.myForm.screen.value += value; } function result(VALUE) { document.myForm.screen.value = eval(document.myForm.screen.value); } function form_reset() { //Type the code here. document.myForm.screen.value = value; }
 <FORM NAME="myForm"> <TABLE BORDER=2> <TR> <TD align="center"> <INPUT TYPE="text" ID="screen" NAME="screen" style="width:99%"><br> </TD> </TR> <TR> <TD> <INPUT TYPE="button" NAME="7" VALUE=" 7 " onclick="update(7)"> <INPUT TYPE="button" NAME="8" VALUE=" 8 " onclick="update(8)"> <INPUT TYPE="button" NAME="9" VALUE=" 9 " onclick="update(9)"> <INPUT TYPE="button" NAME="+" VALUE=" + " onclick="update('+')"> <br> <INPUT TYPE="button" NAME="4" VALUE=" 4 " onclick="update(4)"> <INPUT TYPE="button" NAME="5" VALUE=" 5 " onclick="update(5)"> <INPUT TYPE="button" NAME="6" VALUE=" 6 " onclick="update(6)"> <INPUT TYPE="button" NAME="-" VALUE=" - " onclick="update('-')"> <br> <INPUT TYPE="button" NAME="1" VALUE=" 1 " onclick="update(1)"> <INPUT TYPE="button" NAME="2" VALUE=" 2 " onclick="update(2)"> <INPUT TYPE="button" NAME="3" VALUE=" 3 " onclick="update(3)"> <INPUT TYPE="button" NAME="*" VALUE=" x " onclick="update('*')"> <br> <INPUT TYPE="button" NAME="c" VALUE=" c " onclick="form_reset();"> <INPUT TYPE="button" NAME="0" VALUE=" 0 " onclick="update(0)"> <INPUT TYPE="button" NAME="=" VALUE=" = " onclick="result();"> <INPUT TYPE="button" NAME="/" VALUE=" / " onclick="update('/')"> </TD> </TR> </TABLE> </FORM>

After playing with your code, it seems to be working the way it is supposed to, except for :

function form_reset() {
  //Type the code here.
  document.myForm.screen.value = value;
}

The variable "value" is undefined here. Trying to assign an undefined value will not work and we want this function to reset the content of our calculator input.

Changing this to :

function form_reset() {
  //Type the code here.
  document.myForm.screen.value = '';
}

Will make the "c" button work because we are clearing the string which contains our calculator input.

function update(value) {
  document.getElementById("screen").value += value;
}

function result(value) {
  document.getElementById("screen").value = eval(document.getElementById("screen").value);
  }

function form_reset() {
  document.getElementById("screen").value = '';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM