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

Guidelines for incorporating JS in Framework7

I am developing an application using the framework7. I am facing a challenge where I need to execute some javascript in my page-content, but it is not running as expected. <div class="pages"> <div class="page close-panel" data-page="item"> ...

Creating a fixed footer within a div that is absolutely positioned using CSS

I am looking to implement a sticky footer within an absolutely positioned div element. My initial approach was to position the footer div absolutely as well - within an additional relatively positioned "page" div (which would contain the main content of t ...

Disappearing table borders in print view on Firefox

I have been working on creating a printable table that displays correctly in Chrome. However, when viewed in Firefox, the table borders are not showing up. <body> <table> <tbody> <tr> ...

The thumb of the range input is misaligned with the axis markers

The handle, also known as the knob in this input[type=range] codepen, is not aligning correctly with the ticks. It appears to be off by varying amounts (either left or right) depending on the value. Move the handle to see for yourself. What CSS properties ...

How come a Google Maps API component functions properly even without using *NgIf, but fails to work when excluded in Angular 9?

I recently followed the guide provided in this discussion with success. The method outlined worked perfectly for loading search boxes using this component: map.component.html <input id= 'box2' *ngIf="boxReady" class="controls" type="text" p ...

I have successfully implemented an onChange function with its corresponding set of parameters. However, I now desire to extend its functionality by incorporating

I have an onchange function that triggers when the "pending" option is selected in a select dropdown menu. This function adds a predefined value to an input field. However, I also want this functionality to apply when the page loads. Currently, the "pendin ...

Using Rails and HAML to incorporate looping HTML5 video tags

I have a question regarding how I'm using Rails video_tag to display a video: = video_tag("SMR_video.mp4", :controls => false, :autobuffer => true, :autoplay => true, :loop => true, :id => "hero-video") After implementing the above co ...

Guide on displaying the <html> tag within text using AngularJS

I need to display some data in HTML, which looks like this: <p>abcd efg hijk....(<a href=\"http:\/\/www.facebook.com\/stock\/NBR\">NYSE:NBR<\/a>),, however, there are some HTML tags within ...

What steps do I need to take in order to integrate an mpg video onto my

I am in need of embedding mpg (dvd compliant mpeg2) movie files onto my webpage. Unfortunately, I do not have the ability to convert these videos into any other format. This webpage is solely for personal use, so any solution would be greatly appreciated. ...

Express.js error: Unexpected closing parenthesis after argument list

Here is a snippet of code that I am having trouble with: doc.image('images/pic_1.jpg', 0, 15, scale: 0.25) .text('Scale', 0, 0) I referred to the official PDFkit documentation at PDFKit documentation However, when I tried this co ...

The CSS navigation bar is not properly aligned in the center

This menu was constructed by me: JSBIN EDIT ; JSBIN DEMO Upon closer inspection, it appears that the menu is not centered in the middle of the bar; rather, it is centered higher up. My goal is to have it positioned lower, right in the middle. I ...

I am attempting to properly arrange my navigation links and logo in alignment

I need help aligning the logo in the exact center while keeping the navigation links as they are. Here is how it currently looks: https://i.stack.imgur.com/qOgVJ.jpg My CSS: .logo { display: inline-block; text-align: center; } na ...

JQuery: Issues with attaching .on handlers to dynamically added elements

I'm currently developing a comment system. Upon loading the page, users will see a box to create a new comment, along with existing comments that have reply buttons. Clicking on a reply button will duplicate and add the comment text box like this: $( ...

WP How can I modify a particular thumbnail size with a custom CSS class?

I have been attempting to use add_image_size for my custom thumbnail resize, but it seems to be having trouble maintaining the thumbnail size at 220 x 220. Instead, it keeps changing the height to 167 pixels. As a workaround, I am exploring a CSS-based sol ...

Insert a new key/value pair into a designated object in Javascript

var data = { "2738": { "Question": "How are you?", "Answer": "I'm fine" }, "4293": { "Question": "What's your name?", "Answer": "My name is John" } } var newQuestion = "Where do you live?"; var newAnswer = "I liv ...

Php file not receiving data from ajax post method

forget.php PHP: if (! (empty($_POST['emailforget'])) ) { echo "here in the function"; } else { echo "here"; } AJAX: $("#passreset").on('click', function(e) { var emailforget = $("#tempemail").val(); alert(emailforget); ...

Is it more beneficial to keep a function inside or outside another function if it is only being used within it?

Within the topic at hand, I have a function structured as follows. There are numerous auxiliary functions declared within this function (twice the amount shown in the example) because they are solely utilized by this function. My query is: should I extrac ...

Learn how to trigger an HTTP exception after a failed command in a saga with NestJS CQRS

Currently utilizing the NestJS CQRS pattern to handle interactions between User and UserProfile entities within my system. The setup consists of an API Gateway NestJS server along with dedicated NestJS servers for each microservice (User, UserProfile, etc. ...

How can one discern the most effective method to identify JavaScript code that alters particular HTML content on a webpage?

On my website, I have a <p> tag and I am interested in knowing which JavaScript function is responsible for adding text inside this element. Is there a special method in Chrome to add a listener on this tag and pinpoint the script that writes to it ...

retrieve data properties from an object

Suppose I have the following setup: var myObj = [ { name: 'A', number: 'b1', level: 0 }, { name: 'B', number: 'b2', level: 0 }, ]; I need to figure out how to retrieve all the names and format them like this: ...