Digits disappearing beyond the screen in a JavaScript calculator

I'm currently working on a small calculator project and encountering an issue where the input numbers continue to fill the display even when it's already full. I'd like to limit the input once the display reaches its maximum capacity.

If you're unsure about what I mean, please take a look at the code snippet below:

// Code for defining button variables
const digit0 = document.getElementById("digit0");
digit0.addEventListener("click", input);
// More button definitions...
// Additional event listeners...

// Function for handling user inputs
function input(e) {
  // Logic for processing different key presses and updating the display
}

// Function for calculating results
function calculate() {
  // Implementation for evaluating the expression and displaying the result
}

// Reset and delete functions for clearing the display
function reset() {
  // Clear the display and reset calculation
}

function del() {
  // Delete the last character in the display
}
body {
  // CSS styling for the calculator UI
}

// Additional CSS styles for calculator keys and display
<div class="calc-wrapper">
  <div id="display"></div>
  <div class="keys">
    // HTML structure for the calculator buttons
  </div>
</div>

Answer №1

Your work is truly impressive!

To address the issue, consider limiting the number of characters that can be entered into the displayCurrentResult field. When the limit is reached, determine the desired action to take. Here's a suggested approach:

if (
    (displayCurrentResult.substring(-1) === "*" ||
      displayCurrentResult.substring(-1) === "/" ||
      displayCurrentResult.substring(-1) === "-" ||
      displayCurrentResult.substring(-1) === "+") &&
    (inputValue === "*" ||
      inputValue === "/" ||
      inputValue === "-" ||
      inputValue === "+")
  ) {
    displayCurrentResult = displayCurrentResult.slice(0, -1) + inputValue;
  } else if(displayCurrentResult.length >= 8) {
     // Specify action after reaching the limit here
    return;
  }else {
    displayCurrentResult += inputValue;
  }
  display.innerText = commaSeparator(displayCurrentResult);
}

In the else if() section where nothing is returned, insert the code to execute your desired action upon hitting the character limit. Consider halting number input one step before operators are added.

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 steps should be taken to properly assess an AngularJS provider setup?

My provider definition looks like this: (function(angular) { angular.module('myModule', []) .provider('myService', function () { var service = {}; service.configureSomething = function () { }; service.$get = function () { ...

The ng-click function ceases to trigger after the $location dependency is included in the controller

I need some help with running a ng-click function from my controller. The strange thing is, when I don't use the $location dependency, the ng-click function works fine. But as soon as I add $location to the controller, the ng-click function stops work ...

Ways to divide a buffer in JavaScript

String was created by utilizing the toString method on the buffer. Here is a sample of the resulting string: GET / HTTP/1.1 Host: localhost:8080 Connection: keep-alive Cache-Control: max-age=0 .... Is there a way to parse this string whenever a space (" ...

Arrange the elements according to time in an array

I am in possession of some data retrieved from an API and I am looking to organize it based on the time stamp (iStart). Any suggestions or guidance on how to accomplish this task? The dataset consists of around 12 items, each containing various informati ...

Utilizing BBC gelui within Joomla 3.0 for seamless integration

I am currently using Joomla! 3.0 with the Joomlashape Helix template and I am following a tutorial. You can check out the tutorial here. The tutorial mentions that I need to download RequireJS. Can anyone confirm if RequireJS is compatible with Joomla 3 ...

Utilizing numerous script elements for three.js library

Today, I ventured into the world of three.js for the first time, along with exploring html and js in general. While experimenting with some example code, I encountered an issue. It seems that importing the three.js file from the script tag in my Main.js ...

Issue with node.js readLine where the final line is not being stored in the array

Using Node.js 8.x for capturing standard input and storing it in an array An issue arises where the last line is not being saved in the array I am confused about async and sync in JavaScript, what am I missing? const promise = require('promise&apos ...

What is the best way to incorporate (+/-) buttons to increase or decrease numbers in this code snippet?

Hey everyone, I hope you're all doing well! I need some assistance in transforming this quantity picker from a dropdown to have buttons like the one shown here with plus and minus symbols: https://i.stack.imgur.com/O0uUa.png I would like to impleme ...

Extending the length of the list items and their contents

Take a look at this website. I'm struggling with expanding the submenu list items in IE7. It seems that when you hover over one of the LIs under Restaurants, the green does not fill the entire line. I attempted using {width: 100%}, but it did not sol ...

Firebase (web) deploy encounters an issue due to stripe integration

I recently integrated Stripe into my Firebase function index.js: const stripe = require('stripe')('key'); and created a function for checkout sessions: exports.createCheckoutSession = functions.https.onCall(async(data, context) =&g ...

Checking URL validity with regular expressions in Vue JS

Currently, I am attempting to validate URL strings utilizing a regular expression. The following regex is what I am using for this purpose: var regex = /^(http|https):\/\/+[\www\d]+\.[\w]+(\/[\w\d]+)?/ With thi ...

Is there a way to achieve the same task with Ajax?

Hey there, I am new to the world of JavaScript and AJAX. I have been reading about how to convert a client-side JavaScript variable into a server-side PHP variable by using AJAX. Can someone please provide me with a code snippet using AJAX for this purpose ...

creating a personalized dropdown menu with react javascript

Is it possible to create a chip in a single select dropdown in React? In a multi-select dropdown, a chip is created as shown in the example below. Can we achieve the same effect in a single selection dropdown? const DropdownExampleClearableMultiple = () = ...

Identify a div that manifests within the region of another element

Greetings everyone! I have a target that shoots randomly. I'm trying to make my "winner" div appear when a shot hits the center of the target. I really appreciate any help, I've already attempted collision detection but it doesn't work si ...

The Vue.js error message "Unable to access property 'array_name' as it is undefined" indicates an issue with

I'm currently working on fetching data using Axios requests and storing it in an array. Below is the code I have been using: props: [ 'products', ], data: function () { return { algolia: '', pro ...

"Even as the page scrolls down, the scrollbars stubbornly stay anchored at the

I'm currently working on a webpage that includes a link to an anchor, which should be a straightforward case. The link code looks something like this: <a href="#target">Link</a> And the anchor code looks like this: <a name=" ...

Display or conceal a div based on checkbox selection

I am trying to implement functionality to show/hide a div when a single checkbox is selected. Currently, it works with "Select all" but I am struggling to make it work with a single checkbox. Below is the code for "Select All": JS: <script language=&a ...

JavaScript: When setting focus on a DOM element, the document.activeElement is not automatically updated

I am facing an issue where I need to manually set focus on two buttons consecutively. These buttons are jQuery-Objects stored in an array named pMenus. Below is the code snippet: function OpenSubMenus(pMenus) { pMenus[pMenus.length - 1].get(0).focus() ...

How can background wait for executescript in a Chrome Extension?

I'm currently encountering an issue while developing my first Google Chrome Extension. In my background.js script, I have a scenario where I call script.js every second. Here's a simplified version of the code: script.js: /* Some code */ if (co ...

Dependencies for Grunt tasks

I am facing some issues with a grunt task named taskA that was installed via npm. The task has a dependency on grunt-contrib-stylus, which is specified in the package.json file of taskA and installed successfully. However, when I run grunt default from the ...