I am interested in learning how to utilize the Prompt function in JavaScript, along with the if and else statements, to allow users to input arithmetic symbols and perform

Having some trouble as a beginner and it's driving me crazy; can't seem to figure out what I'm doing wrong. Seeking help with my Javascript code. No errors are showing up, but also not getting any results displayed. Here is the snippet:

    var sumIt;
    var subtractIt;
    var multiplyIt;
    var divideIt;
    var operatorOpt = prompt("Select operator");
    
    function showResult(whatResult) {
        document.write(whatResult);
        document.write("<br>");
    }
    
    var doSomething = function(num1, num2) {
        if (operatorOpt == sumIt) {
            showResult("The result is: " + (num1 + num2));
    
    
        } else if (operatorOpt == subtractIt) {
            showResult("The result is: " + (num1 - num2));
    
        }  else if (operatorOpt == multiplyIt) {
            showResult("The result is: " + (num1 * num2));
    
    
    }  else if (operatorOpt == divideIt) {
            showResult("The result is: " + (num1 / num2));
    
    doSomething(parseInt (prompt("Enter first number: ")) ,  parseInt (prompt("Enter second number: ")))

Answer №1

It appears that there is a missing closing bracket in the definition of the doSomething function. Here is a modified version of the code that should produce the desired output:

var sum = "+";
var subtract = "-";
var multiply = "*";
var divide = "/";
var operator = prompt("Select operator");

function display(whatToDisplay) {
    console.log(whatToDisplay);
    document.write(whatToDisplay);
    document.write("<br>");
}

var doSomething = function(num1, num2) {
    if (operator == sum) {
        display("The result is: " + (num1 + num2));
    } else if (operator == subtract) {
        display("The result is: " + (num1 - num2));
    }  else if (operator == multiply) {
        display("The result is: " + (num1 * num2));
    }  else if (operator == divide) {
        display("The result is: " + (num1 / num2));
    } else {
      console.log("No matching condition found");
    }

 }

 doSomething(parseInt(prompt("Enter first number: ")), parseInt(prompt("Enter second number: ")));

Answer №2

To start, simply create a list of options when prompted:

prompt("Select an operator:" 
+ "\n1. Addition" 
+ "\n2. Subtraction" 
+ "\n3. Multiplication" 
+ "\n4. Division"); 

After that, compare the numbers provided by the user with the chosen operator number.

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

What is causing ngdocs to produce zero files?

I have created a basic project to experiment with grunt-ngdocs (https://www.npmjs.org/package/grunt-ngdocs). But, for some reason, when I attempt to generate documentation, it fails to recognize any comments. Why is this happening? Can someone offer assist ...

The reference to a $scope array in AngularJS has not been properly updated

Check out the code snippet below: var myapp = angular.module('myapp', []); myapp.controller('FirstCtrl', function ($scope) { $scope.people = [ { id: 1, first: 'John', last: 'Rambo' }, { id: 2, first: 'R ...

webgl renderer for cytoscape.js

I have been exploring different layout extensions and have examined various examples from existing extensions like arbor, cola, cose-bilkent, as well as the scaffolding provided here. However, I am facing a roadblock when it comes to integrating a webGL re ...

Tips for utilizing a Three.js curve to guide the movement of a mesh along a specified path

Developing an animation, currently at this stage: http://jsfiddle.net/CoderX99/66b3j9wa/1/ Please avoid delving into the code, it's written in CoffeeScript and may not be beneficial for your mental well-being. Imagine a "nordic" landscape with ship ...

Retrieve information from the MySQL database and display it in the second textbox as you type in the first

This is the interface we are working on. https://i.sstatic.net/Hkr9b.png The PHP file is named "fetching_book_title_for_barcode.php". <?php require_once('db.php'); $response=array(); $sql="select book_title from book where barcode_id LIKE ...

When I log them out, Node.js express always manages to bail me out even when Object is not defined

While attempting to destructure an object in my express middleware: const verifyLoggedInStatus = (req, res, next) => { try { const token = req.cookies['jwt-auth'].token; console.log('token: ', token); req. ...

Attempting to create an array using jQuery's :checked selector

In my table structure below, I have multiple rows with various data: <tr class="row"> <td class="row-checkbox-delete-row"> <input tabindex="-1" class="checkbox-delete-row" type="checkbox" /> </td> <td class="r ...

Delayed callback on blur

I am developing an AutoComplete feature in React that displays a list of suggested completions as the user types into a text box. When a suggestion is clicked, it should trigger a callback function, and the dropdown should disappear when the text box loses ...

Issue with Prototype.js: Headers added to request details cannot be viewed in browser

Looking to enhance Ajax.Request with additional headers, I have constructed the requestHeader object: requestHeaders: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,O ...

Creating a RESTful API

To begin with, I am a newcomer to web frameworks and we are currently using Meteor. In our database, we have a collection of Students: Students = new Mongo.Collection('students'); At the moment, we have defined a Rest API as follows: // Maps t ...

In what way does Google Maps display map information at various zoom levels?

I am interested in developing an intricate electronic circuit using HTML. My goal is to display every aspect of the circuit in different levels of zoom, similar to how Google Maps functions. I am curious about the inner workings of Google Maps and how th ...

How can I trigger a select tag change event in Jquery without any user interaction?

I'm currently facing a small hurdle. I have 3 cascading drop down lists, namely category, subcategory, and subsubcategory. The user picks a value from the category list, which then displays related values in the subcategory list. When the user changes ...

Working with Vue.js to call component methods when the page loads

My payment implementation utilizes vue-js and stripe. I found that the only way to incorporate Stripe with vue-js was through the use of script.onload. Now, I am trying to access some of my methods within the onload function. Specifically, I want to call ...

Transitioning to jQuery version 1.7 and modifications to the event object

After upgrading from jquery 1.6.2 to 1.7, I encountered an issue with changes in the event object parameter on callbacks. Here's a summary of the problem: One of the noticeable impacts was on my jquery-ui (version 1.8.16) "sortables," which started e ...

Steps for displaying detailed information about a single product on an Ecommerce page

Currently in the process of developing my Ecommerce project, I have successfully created a product grid with links to each specific product. However, I am facing an issue where I am unable to view the data of each individual item. Below is the code for my ...

Loading a JSON camera and light in Three.js

In my work with Blender, I am utilizing io_three for exporting an entire scene including a Torus, a Sphere, Suzanne (also known as the Money Head), a Camera, and a Point of Light (Lamp). When I receive the JSON file from this export, it contains these elem ...

Proper technique for efficiently inserting multiple records into Mongodb using Node.js

What is the most effective way to perform bulk inserts into MongoDB using Node.js or any other database? Here's an example code snippet that I've written, but I suspect it may have a flaw as db.close() could be executed before all asynchronous c ...

Utilizing the `filterBy` function with a custom select list that changes dynamically

I'm currently in the process of constructing a form with an extensive selection of drop-down items utilizing vue.js. My approach involves implementing the dynamic select list as detailed in this documentation: However, I am interested in providing us ...

Does the header show up when you scroll?

Recently, I encountered a project where I needed a different header to appear when the page was scrolled past the main one. If you want to check out my code, here's a link to a fiddle: https://jsfiddle.net/a7tLdsov/3/ I've tried some JavaScrip ...

Tips for handling multi-line input in a textarea when the user presses the "enter/return" key

Trying to solve a coding issue: ... <textarea name="TextArea1" id="TextArea" style="height ; width" ></textarea> ... <script type="text/javascript"> var txt_element = document.getElementById("TextArea"); document.write (txt_element ...