What is the proper way to incorporate parentheses (either "(" or ")") on the JavaScript calculator's output screen?

This is the customized button I made for the parentheses.

 <div class="col">
          <button class="parentheses rounded-pill  btn-outline-primary btn btn-lg" id="keyButton" data-key="operator"&qt;()</button>
</div>

I have a specific requirement where I want to display "(" only if there is no number on the calculator display. If there is already a number on the display, then I need to add ")" to it.

Below is the JavaScript code I have implemented to achieve this functionality.

for (let i = 0; i < keyButton.length; i++) {    // Iterates through keyButton to fetch values
  
  // console.log(keyButton[i].textContent);    // Output all keyButton values
  
   keyButton[i].addEventListener('click', function () {
     
    // console.log(keyButton[i].textContent);
     
      if (mathOperators.includes(keyButton[i].textContent)){
        console.log('operator');
      }
      if (keyNumbers.includes(keyButton[i].textContent)) {
        console.log('number');
      }
      if (keyButton[i].textContent === '=') {
        count = eval(assigned);
      }
      if (keyButton[i].textContent === 'C') {
        // Clear entire screen
      }
      if (keyButton[i].textContent === '<-') {
        // Clear one value
      }
      if (keyButton[i].textContent === '(') {
        console.log("(")
      } else
      if (keyButton[i].textContent !== "(") {
        console.log(")")
      }
      
      
     updateScreen(keyButton[i].textContent);
   });
  
}


function updateScreen (kb) {
  
    displayNum.textContent = assigned+=kb;   // Shows the current number on the calculator
    answer.textContent = count;
    backspace.removeAttribute('disabled');
  
}

const mathOperators = ['+', '*', '/', '-', '=', 'C', '+/-', '%', '()', '(-', '.', '<-'];

Upon testing, I found that the button always displays "()" regardless of the scenario, instead of showing either "(" or ")".

Answer №1

Your request has been successfully addressed. By clicking the button (), you will receive either ( or ) depending on the current display value.

const displayNum = document.querySelector('.displayValue');
const keyButton = document.querySelectorAll('#keyButton');
const backspace = document.querySelector('.backSpace');
const answer = document.querySelector('.autoUpdatedAnswer');

// Defining Variables
let count = "",
  result, assigned = "",
  operator = "";
const mathOperators = ['+', '*', '/', '-', '=', 'C', '+/-', '%', '()', '(-', '.', '<-'];
const keyNumbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'];

// Loop through keyButton values
for (let i = 0; i < keyButton.length; i++) {

  keyButton[i].addEventListener('click', function() {

    var keyboardValue = keyButton[i].textContent;
    if (mathOperators.includes(keyButton[i].textContent)) {
      console.log('operator');
    }
    if (keyNumbers.includes(keyButton[i].textContent)) {
      console.log('number');
    }
    if (keyButton[i].textContent === '=') {
      count = eval(assigned);
    }
    if (keyButton[i].textContent === 'C') {
      // clear entire screen
    }
    if (keyButton[i].textContent === '<-') {
      // clear one value
    }
    if (keyButton[i].textContent === '(') {
      console.log("(")
    } else
    if (keyButton[i].textContent !== "(") {
      console.log(")")
    }

   if (keyboardValue === '()') {
      if (/\w*\d{1,}\w*/g.test(assigned)) {
        keyboardValue = ')'
      } else {
        keyboardValue = '('
      }   
    }

    updateScreen(keyboardValue);
  });

}

// Function to update the screen
function updateScreen(kb) {
    
  displayNum.textContent = assigned += kb;
  answer.textContent = count;
  backspace.removeAttribute('disabled');

}
.screen {
  text-align: right;
}

.c1, .c2 {
  background-color: white;
  border: 2px solid blue;
}

#keys {
  display: grid;
  align-items: center;
}

button:hover {
  background-color: #6495ED;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
    
    <link rel="stylesheet" href="style.css" type="text/css" media="all" />

    <title>JavaScript Calculator</title>
  </head>
  <body>
    
    <div class="container c1 mt-5 w-50 border-bottom p-5 rounded-top">
      <div class="row">
        <div class="col">
          <div class="screen">
            <h1 class="displayValue">0</h1>
            <h2 class="autoUpdatedAnswer"></h2>
          </div>
        </div>
      </div>
      <div class="row">
        <div class="col">
          <button class="backSpace rounded-pill btn btn-outline-primary btn-lg" id="keyButton" data-key="operator" disabled value="backspace"><-</button>
        </div>  
      </div>
    </div>
    
    <div class="container c2 w-50 rounded-bottom" style="height: 400px; text-align: center;" id="keys">           
        <!-- Buttons for calculator operations -->
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>
    <script src="script.js" type="text/javascript" charset="utf-8"></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

Combining PouchDB with Vue.js for seamless integration

Has anyone successfully integrated PouchDB / vue-pouch-db into a Vue.js application before? I encountered an error when attempting to define the PouchDB database. Here are the definitions I tried: import PouchDB from 'pouchDB' or import PouchDB ...

What causes an AJAX POST request to fail?

While working on a simple HTML page with a form, I encountered an issue with my POST request failing without any response from the server. Can someone please help me figure out what I'm doing wrong? function createRequest(url, body) { var respons ...

What could be causing the computed property in Vue 2 component to not return the expected state?

I'm encountering an issue with my Vue component where it fails to load due to one of its computed properties being undefined: Error: Cannot read properties of undefined (reading 'map') Here is the snippet of the computed property causing ...

Using PM2 to Manage Your PHP Scripts in Cluster Mode

Currently, I have been effectively managing single instances of PHP daemons with PM2, and so far everything is running smoothly! When it comes to managing Node.js/IO.js apps with PM2, I can easily launch them in cluster mode without any issues. However, t ...

Inserting a PHP variable ($username) into a form field

<form method="POST"> <h1>Contact Us</h1> <span><h2 class="required">*Required</h2></span> <div class="input-group"> <label class="sr-only">First Name</label> <input class="text" ...

Troubleshooting the issue: AngularJS not functioning properly with radio button selection to show specific div containing input field

Looking for some help with radio buttons: I need the selection of radio buttons to display their respective input boxes. I have included a snippet of my HTML and controller code below. In my controller, I am using ng-change to call a function that uses jQu ...

"What is the best way to manipulate arrays in vue.js using the map function

I'm currently dealing with a Vue code that incorporates anime.js. My code has grown substantially to over 1500 lines. In order for Stack Overflow to accept my question, I have only included 5 items of my sampleText, even though it actually consists of ...

Unable to assign headers once they have already been sent to the recipient - a Node.js error

Encountering an error message stating "Cannot set headers after they are sent to the client." I've researched and it seems like multiple callbacks may be causing this issue. However, I'm struggling to find a solution. Any assistance in resolving ...

Jumping Sticky Table Headers

Looking for a solution to prevent the table header from moving when scrolling through the data: tbody { overflow-y: scroll; } thead, tbody tr { display: table; width: 100%; table-layout: fixed; text-align: left; } thead, th { position: sti ...

Execute an asynchronous request using Javascript to communicate with a Spring Controller

I've created a JSP page that includes some JavaScript code: function sendData(tableID) { var table = document.getElementById(tableID); var dataArray= new Array(); for (var i = 1;i<table.rows.length; i++){ var row = table. ...

choose exclusively the text within the elementor navigation menu

I've been tinkering with this issue for a few hours now. I have a vertical Elementor navigation menu and I'd like to add a hover effect to it. So far, I can only select the entire column and apply the effect to that, not just the length of the t ...

What are some strategies to enhance the efficiency of this code and reduce repetition?

Here's an overview of the component in question export default () => { const { currentUser, logout } = useAuth(); const [sideBarOpen, setSideBarOpen] = useState(false); const theme = useTheme(); const classes = useStyles(); const isSmall ...

Capturing numerous data points with JavaScript

<span> <label class="label">Color</label> <span class="foo"><input name="Color" value="Blue" class="customs" maxlength="100" type="text"/></span> </span> </span> <span> <label cla ...

Retrieving form data in Servlet

Just began working with servlets and encountered an issue. I am trying to upload a file to my server using a servlet, while also sending a text value (the file name) to be changed on the server side. The problem arises when I submit the form data to the se ...

Updating displayed images in HTML using Python and Flask based on passed data

return render_template('homepage.html',imgName=filenameD) PYTHON <img src= {{ name }} alt="something" style="width:500px;height:600px;"> HTML I am attempting to dynamically change the image displayed on my website usi ...

How can one determine the proper size for a border?

Can the border of a div be larger than the actual dimensions of the div itself? For instance, if the div is 10x10 in size, is it possible to have a border that is 20x10? ...

What is the best way to use jQuery to toggle the visibility of a <panel>?

My objective is to display a panel with two labels on a button click, but I'm facing issues achieving this functionality. When I click on the button (id=Button1), the panel (id=anspanel) should appear, but it remains hidden even after clicking the but ...

Delving into the World of CSS

I have been working on changing the background image using this JavaScript code, but I am not sure what to reference in the CSS file. Despite reading through everything, my screen still remains blank. $(function() { var body = $('body'); var bac ...

Data binding in Vue does not function properly within functional components

Clicking the button will cause the number n to increase, but the UI will display it as constant 1. <script> let n = 1 function add() { console.log(n) return ++n } export default { functional: true, render(h, ctx) { return (<div> ...

Can the functionality of ngIf and async pipe be replicated within the component's code?

With a form component and a thank you page, I am faced with the challenge of sharing data between these two components using rxjs ReplaySubject. The full code listings can be found here. In my implementation, I am utilizing ngIf and the async pipe to hand ...