Creating a simple calculator using HTML and JavaScript

I am struggling to create an HTML code for performing basic mathematical operations like addition, subtraction, division, and multiplication with multiple numbers. I have tried adding some CSS for styling purposes, but my main concern is getting the code to work correctly. I am using JavaScript as well. Can someone please help me figure out what I'm doing wrong?

<html>
<head>

<body bgcolor="FFFCC">
<table border="0" cellpadding="0"
cellspacing="1" style="border-collapse: collapse"
bordercolor="#1111" width="50%">

<hi><p align="center">CALCULATOR</p></hi><br>
<script language="javascript">
function ADD()
{
var first = parseFloat(txtNumber1.value);
var second = parseFloat(txtNumber2.value);
var Ans = first + second;
txtAnswer.value = Ans;
}

function MINUS()
{
var first = parseFloat(txtNumber1.value);
var second = parseFloat(txtNumber2.value);
var Ans = first - second;
txtAnswer.value = Ans;

function DIVIDE()
{
var first = parseFloat(txtNumber1.value);
var second = parseFloat(txtNumber2.value);
var Ans = first / second;
txtAnswer.value = Ans;
}

function MULTIPLY()
{
var first = parseFloat(txtNumber1.value);
var second = parseFloat(txtNumber2.value);
var Ans = first * second;
txtAnswer.value = Ans;
}
function MODULO()
{
var first = parseFloat(txtNumber1.value);
var second = parseFloat(txtNumber2.value);
var Ans = first % second;
txtAnswer.value = Ans;
}

</script> 
</head>



<input type="text" name="txtNumber1"/><br>
<input type="text" name="txtNumber2"/><br>
<input type="button" name="butAnswer" 
value="+" onclick="ADD()"/>
<input type="button" name="butAnswer"
value="-" onclick="MINUS()"/>
<input type="button" name="butAnswer"
value="/" onclick="DIVIDE()"/>
<input type="button" name="butAnswer"
value="*" onclick="MULTIPLY()"/>
<input type="button" name="butAnswer"
value="%" onclick="MODULO()"/><br>
<input type="text" name="txtAnswer"/>

</table>
</body>
</html>

Answer №1

You must remember to properly reference your input elements!

Take a look at this scenario

var num1=parseFloat(inputNumber.value);

The input element named "inputNumber" is not defined.

To fix this issue, use:

var num1=parseFloat(document.getElementsByName('inputNumber')[0].value);

Answer №2

Here are some adjustments to make to these lines of code:

let firstNumber = parseFloat(document.getElementsByName("txtNumber1")[0].value);
let secondNumber = parseFloat(document.getElementsByName("txtNumber2")[0].value);

document.getElementsByName("txtAnswer")[0].value = ans;

Answer №3

  <html>
<head>

</head>
<body bgcolor="FFFCC">

  <table width="50%" align="center">
    <tr><td colspan="2"><hi><p>CALCULATOR</p></hi></td></tr>
    <tr><td><input type ="text" id="txtNumber1" placeholder="Enter first number"/><input type ="text" id="txtNumber2" placeholder="Enter second number"/> <input type ="text" id="txtAnswer"/></td>
<tr><td><input type ="button" name="butAnswer" 
value="+" onclick="ADD()"/>
<input type ="button" name="butAnswer"
value="-" onclick="MINUS()"/>
<input type ="button" name="butAnswer"
value="/" onclick="DIVIDE()"/>
<input type ="button" name="butAnswer"
value="*" onclick="MULTIPLY()"/>
<input type ="button" name="butAnswer"
       value="%" onclick="MODULO()"/></td></tr>
    <tr>

</table>

<script language= "javascript">
var answer=document.getElementById("txtAnswer")
function ADD()
{

  var number1=document.getElementById("txtNumber1")
  var number2=document.getElementById("txtNumber2")
    number1=parseFloat(number1.value)
    number2=parseFloat(number2.value)
var Sum =number1+number2;
answer.value=Sum;
}

function MINUS()
{

  var number1=document.getElementById("txtNumber1")
  var number2=document.getElementById("txtNumber2")
    number1=parseFloat(number1.value)
    number2=parseFloat(number2.value)
var Diff =number1-number2;
answer.value=Diff;
}
function DIVIDE()
{

  var number1=document.getElementById("txtNumber1")
  var number2=document.getElementById("txtNumber2")
    number1=parseFloat(number1.value)
    number2=parseFloat(number2.value)
var Quo =number1/number2;
answer.value=Quo;
}

function MULTIPLY()
{

  var number1=document.getElementById("txtNumber1")
  var number2=document.getElementById("txtNumber2")
    number1=parseFloat(number1.value)
    number2=parseFloat(number2.value)
var Prod =number1*number2;
answer.value=Prod;
}
function MODULO()
{

  var number1=document.getElementById("txtNumber1")
  var number2=document.getElementById("txtNumber2")
    number1=parseFloat(number1.value)
    number2=parseFloat(number2.value)
var Remainder =number1%number2;
answer.value=Remainder;
}   

</script> 
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discover the true width of the unordered list structure Forest

One of my projects involves creating family trees using CSS and unordered lists. It works great, except when the tree is wider than the screen, causing it to wrap awkwardly. To solve this issue, I implemented the following CSS: #treewrapper { margin: 10px ...

Comparing npm install --save versus npm install --save-dev

Hey everyone, I've been using npm install -g to globally install node modules/packages, but I'm a bit confused about the --save and --save-dev options. I tried looking it up on Google, but I'm still not entirely sure. Can you guys help clar ...

What methods are recommended for expanding the size of a select/dropdown menu?

Managing a long list of values can be challenging, especially when it continues to grow. Consider the following example: <select> <option value="1">1, some test</option> <option value="2">2, some text</option> <optio ...

What is the process for creating a modal transition?

I am attempting to add animation to a modal using a transition effect. My goal is to open it slowly, either from the center of the screen or from the bottom. However, I am struggling to understand how this can be achieved... While searching on Google, I c ...

Display and Conceal Progress Bar during Page Load

I've recently built a web-page using ASP.NET, and I'm looking to enhance it with a progress bar as the page tends to take a few minutes to load. My plan is to include a Show Progress Bar function at the beginning of the Page_Load function and hi ...

Do async functions in javascript function synchronously in reality?

I am currently exploring the inner workings of asynchronous code in Javascript. From my understanding, there exists a single thread in JS responsible for executing tasks in a queue. It can progress to the next task only after finishing the current one, whe ...

The process of batch file conversion and how to effectively utilize it

I am facing an issue with a small batch script that I have been working on. The purpose of this batch script is to execute a Javascript file that converts an XML file to a csv file, followed by running a Python script to analyze the created csv file and ge ...

Is there a content delivery network (CDN) link available for the object spread polyfill in Javascript?

Can someone help me find a polyfill for the object spread operator in javascript? I'm looking for either a cdn link or a method to achieve this using es5 javascript. var x = { example: 456, sample: 789 } var y = { ...x, result: 321 } ...

The list style image is failing to display properly due to an issue with the external

Below is the HTML code that I have written: <!DOCTYPE html> <html> <head> <style> ul{ list-style-image:url('img/grey.png'); } </style> <body> <ul> <li>Coffee</li> <li>Tea</li&g ...

Interactive canvas box in motion with directional arrows

I am attempting to create a basic canvas box that moves using arrow keys. Here is the code: Here's the code snippet: $(function() { var n = 3; var xD = 0; var yD = 0; var canvas = document.getElementById("canvas"); var ctx = canvas.getCon ...

Differences in font size of Text Sprites between ThreeJS's WebGL renderer and Canvas renderer

I am currently working with Three JS to develop a 3D graph and I am facing an issue with displaying units of the graph as THREE.SPRITE. To create a SPRITE, I first generate a canvas element and add text to it. Then I proceed to create a THREE.Texture using ...

The grunt-bower-task tool seems to be experiencing issues as it removes coffeescript from the bower_components directory and subsequently raises an error

Upon executing grunt bower -v, the output displayed is as follows: The process starts with initialization, followed by reading and registering tasks from various Npm modules. Output includes actions related to copying, parsing, installing dependencies, an ...

Issues with executing the intended task for a jQuery onclick function

I have a unique jQuery script set up where when #block4 is clicked, the .maincontent div will show. Initially it works perfectly by showing and then hiding the div. However, after the first two clicks, the .maincontent div shows and immediately disappears. ...

A comprehensive guide on incorporating Jest for testing localStorage

I have attempted to mock localStorage following the advice from another source, but I am struggling to get the tests to pass despite several attempts. Below is the code for the localStorage mock: class LocalStorageMock { constructor() { this.stor ...

Conditionally displaying a select element using Ng-if

Is there a way to display content based on the user's selection in an HTML form? Here is how I attempted to do it: <select class="form-control" id="Intervencion" > <option selected disabled></option> <option (click)="show ...

Issue with Adding Additional Property to react-leaflet Marker Component in TypeScript

I'm attempting to include an extra property count in the Marker component provided by react-leaflet. Unfortunately, we're encountering an error. Type '{ children: Element; position: [number, number]; key: number; count: number; }' is n ...

Accessing values from an array within a JSON object using jqGrid

Here is an example of my JSON data: [{"codDiretor":"123", "nomeDiretor":"Nome do Diretor", "data":"29/01/2014", "documentos":[{"codDocumento":"1", "nomeDocumento":"Primeiro Doc"}, {"codDocumento":"2","nomeDocumento":"Segundo Doc"}] ...

Enhance the functionality of the custom transaction form in NetSuite by incorporating new actions

I'm currently working on incorporating a new menu option into the "Actions" menu within a custom transaction form in NetSuite. While I can successfully see my selection in the Actions Menu on the form, I'm running into an issue with triggering th ...

Allow access to the configuration file for a JavaScript file located in the public directory of an Express application

I have a specific question regarding the folder structure of my Express app. app │ │ └───config │ │ config.js │ │ └───public │ │ │ └───javascripts │ │ exportable.js │ ...

Working with Vue.js: Binding to dynamically generated form elements

I am facing an issue where form elements are not available in the html document until an inline script runs on page load. In Vue.js, how can I bind to these form elements after the page loads? While with jQuery I could use a $('.element').each(), ...