Javascript Calculator with Dual Input Fields

I have been given a task to create a calculator by tomorrow using Javascript. Unfortunately, I am currently taking a distance course and Javascript has just been introduced in this assignment. While I am familiar with HTML and CSS, Javascript is something that I find really challenging.

Although I have started working on the code for the calculator, I am stuck because I cannot seem to find any relevant resources online that explain how to create a similar calculator or provide a simple explanation of Javascript. The calculator should not feature a submit button and its design is not important, but it needs to include two text fields.

function Calculate() {
  var number1 = document.getElementById("number1").value;
  var number2 = document.getElementById("number2").value;
  number1_parsed = parseInt(number1);
  number2_parsed = parseInt(number2);
  if (number1_parsed) {} else
    alert("Wrong characters");
  return false;
} {
  sum = number1_parsed + number2_parsed;
  alert("Sum: " + sum);
}
<div id="calculator">
  <h1> Calculator </h1>
  <form name="kalkylator">
    <input type="text" name="number1" id="number1" size="10" />
    <input type="text" name="number2" id="number2" size="10" />
    <input type="button" onclick="Calculate();" id="calculate" value="Result">
  </form>
</div>

Answer №1

Ensuring your code is well-formatted is crucial for easier debugging. Accurate indentation plays a key role in this process. If these guidelines were followed, you would have likely spotted the issues with the curly braces.

In addition, there are inconsistencies in your variable naming.

For instance:

  • You missed an open curly brace ({) after the else statement
  • There is an unexpected open curly brace before the line:
    summa = number1_parsed + number2_parsed;
  • You called parseInt(tal1); but the variable should be number1, not tal1
  • The variable used to store the sum is sum, while the alert reference uses summa

var number1 = document.getElementById("number1");
var number2 = document.getElementById("number2");

function Calculate() {
  var number1_parsed = parseInt(number1.value);
  var number2_parsed = parseInt(number2.value);
  if (isNaN(number1_parsed) || isNaN(number2_parsed)) {
    alert("Wrong characters");
    return false;
  }

  var sum = number1_parsed + number2_parsed;
  alert("Sum: " + sum);
}
<div id="calculator">
  <h1> Calculator </h1>
  <form name="kalkylator">
    <input type="text" name="number1" id="number1" size="10" />
    <input type="text" name="number2" id="number2" size="10" />
    <input type="button" onclick="Calculate();" id="calculate" value="Result">
  </form>
</div>

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

Utilizing a responsive design with a bootstrap grid system, featuring expandable columns for

After creating a bootstrap grid page, I am facing an issue with the layout on mobile screens. My problem arises when trying to reorder the cards properly for mobile view. Here is my current logic: <div class="row"> <div *ngFor="let col of [1, ...

Graph only displays data after button is clicked

I have been working on customizing this jsfiddle to display database data. Check it out here: http://jsfiddle.net/jlbriggs/7ntyzo6u/ Using JSON, I am fetching data from my database and editing chart1 to display the database data: var chart, chartOption ...

PHP error: Index not defined

One challenge I’m encountering is with a dating site form that includes the following categories: firstname,lastname,username,password,email,mysex,yoursex,relationship,date of birth, and country I've completed the PHP code to send information to a ...

Step-by-step guide to inserting an image into a Table Cell

I want to include my PDF image at the conclusion of the text in my table cell When it comes to my Table, I'm hoping that the image can be combined with the text seamlessly after it finishes <TableCell component="th" scope="row" className = {class ...

Version 13 of the Discord slash command encounters an "interaction failed" error

After implementing the slash commands in Discord v13 as per the instructions on discordjs.guide, I encountered an issue when trying to use the commands - interaction failed. Here is a snippet of my code: // Here goes the code const { Client, Collection, ...

Creating a conditional property in TypeScript based on an existing type - a comprehensive guide

Imagine if I had the following: type Link = { text: string; link: string; } interface BigLink extends Link { some: number; something: string; else: string; } However, there's a variable that shares all these properties except for the fact ...

The canvas div wrapper flexbox item is in need of scrollbars

I am looking to display a canvas that may be larger than the viewport size. The layout structure will include navigation on the left and controls on the right, with the canvas positioned in between them. When the canvas is too large for the screen, I wan ...

How to ensure that a div element occupies the entire height of the webpage

After developing a small app in Angular, I'm looking to make the container element expand to the full height of the page, even when the content doesn't fill the entire space. On larger screens, the page doesn't stretch as desired. Here' ...

transferring information between controllers and saving it persistently in AngularJS even after refreshing the

What is the best way to share data (Object) between controllers with different routes and prevent data loss after a page reload? I have an object that I need to use to prefill form values on my destination page based on choices made on my source page. S ...

Managing multiple sets of radio buttons using the useState hook

Within my renderUpgrades-function, I handle the options of an item by including them in radio-button-groups. Each item has multiple options and each option has its own radio-button-group. Typically, a radio-button-group can be managed using useState, wit ...

Display personalized error messages using jQuery and PHP

I implemented an Ajax autocomplete feature on an input field within a form using jQuery. Here are the ajax settings I have set up: $.ajax({ type: "POST", url: myUrl, data: $("#id__form").serialize(), success: function(data){ ...

PHP - Extract Information from Table Upon Form Submission without User Input

I'm facing a challenge with my web form that includes a table allowing users to delete rows before submitting. Although there are no input fields in the table, I need to capture the data from these rows when the form is submitted. The issue is that th ...

The event for closing the React Select MUI dropdown does not trigger when selecting multiple options

When multiple values are selected from the dropdown and clicked outside, the dropdown closes but the onClose event fails to trigger. I need to filter data based on the selections made in the dropdown. For example, looking at the image below, I want to dis ...

Using JavaScript to dynamically change the IDs of multiple select elements during runtime

I am facing an issue when trying to assign different IDs to multiple select elements at runtime. The number of select elements may vary, but I need each one to have a unique ID. Can anyone assist me in locating the select elements at runtime and assignin ...

Tips for minimizing the need to copy the entire dojo library each time you create a new Java EE package for deployment on GlassFish

Currently, I am diving into comet programming and utilizing the cometd implementation along with the JavaScript dojo library before deploying my war files to GlassFish. The issue I have encountered is that every time I create a new project, I find myself i ...

Having trouble with PHP Storm and Vue component not working? Or encountering issues with unresolved function or method in your

I have been struggling with this issue for days and cannot seem to find a solution online. Being new to Vue.js, I am currently working on a TDD Laravel project: My goal is to add the standard Vue example-component to my app.blade.php as follows: app.bla ...

JavaScript can be utilized to generate an array containing duplicated phrases from a given text

Here's a simple concept: you enter text in a textarea, click "send," and receive a list of recurring phrases. When I say phrases, I mean sequences of two or more words that repeat. While I can identify single words, detecting these phrases is where I& ...

Ways to retrieve only the chosen option when the dropdown menu features identical names

How can I retrieve only the selected value from the user, when there are multiple select options with the same class name due to dynamic data coming from a database? The goal is to submit the data using Ajax and have the user select one option at a time. ...

Is there a way to set the same href link for the active class in the navbar using bootstrap-vue?

I am currently utilizing this navbar. It works fine when the href links are unique, but I encounter an issue when two pages share the same link - the active class is applied to both list items with that link in the manner I have written. Vue.component(& ...

Dropdown Box Internal Link Selector Code

On the lookout for a way to add a combo box on my website's homepage, which can direct users to specific internal links once the correct value is chosen. Here's the test code I've come up with so far, but it doesn't seem to be working a ...