I'm having trouble with certain JavaScript functions on my website - some are working fine, but others aren't. Any suggestions on what I should do

I just finished developing a calculator using HTML, CSS, and Javascript. It works flawlessly for all numbers 1 through 9 and the operators +, -, *, /, and %. However, I am facing issues with the number 0, C, and = buttons not functioning properly.

Upon inspecting the code, I noticed that the logic for the non-working buttons is quite similar to the ones that work correctly, making it challenging for me to identify the root cause of the problem.

Below is a snippet of the problematic code:

 <!--Code block will go here--> 

Could you please assist me in pinpointing the issue?

In addition, I attempted to create a rule where the input field with the id "result" would automatically update whenever there was a change in the input with the id "calculation," but unfortunately, it did not produce the desired outcome.

Answer №1

To customize your calculator, ensure that you assign the subtract button's id attribute to "subtract" and then attach an event listener to the element with the id zero:

document.getElementById("zero").addEventListener("click", () => {
  document.getElementById("calculation").value += "0";
});
document.getElementById("one").addEventListener("click", () => {
  document.getElementById("calculation").value += "1";
});
document.getElementById("two").addEventListener("click", () => {
  document.getElementById("calculation").value += "2";
});
document.getElementById("three").addEventListener("click", () => {
  document.getElementById("calculation").value += "3";
});
document.getElementById("four").addEventListener("click", () => {
  document.getElementById("calculation").value += "4";
});
document.getElementById("five").addEventListener("click", () => {
  document.getElementById("calculation").value += "5";
});
document.getElementById("six").addEventListener("click", () => {
  document.getElementById("calculation").value += "6";
});
document.getElementById("seven").addEventListener("click", () => {
  document.getElementById("calculation").value += "7";
});
document.getElementById("eight").addEventListener("click", () => {
  document.getElementById("calculation").value += "8";
});
document.getElementById("nine").addEventListener("click", () => {
  document.getElementById("calculation").value += "9";
});
document.getElementById("period").addEventListener("click", () => {
  document.getElementById("calculation").value += ".";
});
document.getElementById("add").addEventListener("click", () => {
  document.getElementById("calculation").value += "+";
});
document.getElementById("subtract").addEventListener("click", () => {
  document.getElementById("calculation").value += "-";
});
document.getElementById("multiply").addEventListener("click", () => {
  document.getElementById("calculation").value += "*";
});
document.getElementById("divide").addEventListener("click", () => {
  document.getElementById("calculation").value += "/";
});
document.getElementById("percentage").addEventListener("click", () => {
  document.getElementById("calculation").value += "*(1/100)";
});

//clear calculation
document.getElementById("clear").addEventListener("click", () => {
  document.getElementById("calculation").value = "0";
});

// get result
document.getElementById("getResult").addEventListener("click", () => {
  document.getElementById("result").value = eval(document.getElementById("calculation").value);
});
:root {
    --main-color: darkblue;
    --secondary-color: blue;
    --tertiary-color: #318ce7;
    --dark-color: #444;
    --light-color: #fafafa;
}
body {
    font-family: "Montserrat", sans-serif;
    background-color: var(--light-color);
    color: var(--dark-color);
    margin-top: 0px;
    margin-bottom: 0px;
    display: flex;
    align-content: center;
    align-items: center;
    justify-content: center;
    height: 100vh;
}
.calculator {
    
    box-shadow: var(--main-color) 1px 1px 1em;
    border-radius: 1em;
    height: fit-content;
    width: 370px;
    background-image: linear-gradient(-135deg,var(--secondary-color),var(--tertiary-color),var(--secondary-color));
    overflow: hidden;
}
.output {
    background-image: linear-gradient(-45deg,var(--main-color),var(--secondary-color));
    color: var(--tertiary-color);
    padding: 2em 0px;
}
.result,.calculation {
    display: flex;
    flex-direction: row-reverse;
    align-content: center;
    align-items: center;
    justify-content: end;
}
#result,#calculation {
    padding: 0.3em 10px;
    background-color: transparent;
    color: var(--light-color);
    border: none;
    text-align: right;
    font-size: inherit;
}
::placeholder {
  color: var(--light-color);
}
#result {
    font-size: 1.3em;
}
.result {
    height: 50px;
    font-size: 30px;
}
.calculation {
    height: 40px;
    font-size: 25px;
}
.keyboard {
    padding: 20px 10px;
    display: grid;
    grid-template-columns: auto auto auto auto;
    grid-template-rows: auto auto auto auto auto;
}
button {
    margin: 0.2em 0.2em;
    border: none;
    border-radius: 0.2em;
    height: 40px;
    opacity: 50%;
    color: var(--main-color);
    font-size: 15px;
    font-weight: bolder;
}
button:hover {
    background-image: linear-gradient(-45deg,var(--secondary-color),var(--tertiary-color),var(--secondary-color));
    color: var(--light-color);
    box-shadow: var(--main-color) 1px 1px 1em;
    transition-duration: 400ms;
}
button:active {
    background-image: linear-gradient(-45deg,var(--main-color),var(--secondary-color));
    color: var(--light-color);
    opacity: 100%;
    transition-duration: 400ms;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Calculator</title>
    <link rel="stylesheet" href="index.css" />
  </head>
  <body>
    <div class="calculator">
      <section class="output">
        <section class="result">
          <input id="result" placeholder="0" disabled />
        </section>
        <section class="calculation">
          <input id="calculation" disabled placeholder="0" />
        </section>
      </section>
      <section class="keyboard">
        <button id="clear">C</button>
        <button id="brackets">( )</button>
        <button id="percentage">%</button>
        <button id="divide">/</button>
        <button id="seven">7</button>
        <button id="eight">8</button>
        <button id="nine">9</button>
        <button id="multiply">X</button>
        <button id="four">4</button>
        <button id="five">5</button>
        <button id="six">6</button>
        <button id="subtract">-</button>
        <button id="one" class="getResult2">1</button>
        <button id="two">2</button>
        <button id="three">3</button>
        <button id="add">+</button>
        <button id="change-sign">+/-</button>
        <button id="zero">0</button>
        <button id="period">.</button>
        <button id="getResult">=</button>
      </section>
    </div>
    <script type="text/javascript" src="index.js"></script>
  </body>
</html>

Answer №2

You encountered two distinct problems. First, there was no event listener set for the ID zero. Second, the subtract button did not have an ID assigned, causing the script to fail at the getElementById call and subsequent script execution. The revised code below resolves these issues:

document.getElementById("zero").addEventListener("click", () => {
  document.getElementById("calculation").value += "0";
});
document.getElementById("one").addEventListener("click", () => {
  document.getElementById("calculation").value += "1";
});
document.getElementById("two").addEventListener("click", () => {
  document.getElementById("calculation").value += "2";
});
document.getElementById("three").addEventListener("click", () => {
  document.getElementById("calculation").value += "3";
});
document.getElementById("four").addEventListener("click", () => {
  document.getElementById("calculation").value += "4";
});
document.getElementById("five").addEventListener("click", () => {
  document.getElementById("calculation").value += "5";
});
document.getElementById("six").addEventListener("click", () => {
  document.getElementById("calculation").value += "6";
});
document.getElementById("seven").addEventListener("click", () => {
  document.getElementById("calculation").value += "7";
});
document.getElementById("eight").addEventListener("click", () => {
  document.getElementById("calculation").value += "8";
});
document.getElementById("nine").addEventListener("click", () => {
  document.getElementById("calculation").value += "9";
});
document.getElementById("period").addEventListener("click", () => {
  document.getElementById("calculation").value += ".";
});
document.getElementById("add").addEventListener("click", () => {
  document.getElementById("calculation").value += "+";
});
document.getElementById("subtract").addEventListener("click", () => {
  document.getElementById("calculation").value += "-";
});
document.getElementById("multiply").addEventListener("click", () => {
  document.getElementById("calculation").value += "*";
});
document.getElementById("divide").addEventListener("click", () => {
  document.getElementById("calculation").value += "/";
});
document.getElementById("percentage").addEventListener("click", () => {
  document.getElementById("calculation").value += "*(1/100)";
});

//clear calculation
document.getElementById("clear").addEventListener("click", () => {
  document.getElementById("calculation").value = "0";
});

// get result
document.getElementById("getResult").addEventListener("click", () => {
  document.getElementById("result").value = eval(document.getElementById("calculation").value);
});
:root {
    --main-color: darkblue;
    --secondary-color: blue;
    --tertiary-color: #318ce7;
    --dark-color: #444;
    --light-color: #fafafa;
}
body {
    font-family: "Montserrat", sans-serif;
    background-color: var(--light-color);
    color: var(--dark-color);
    margin-top: 0px;
    margin-bottom: 0px;
    display: flex;
    align-content: center;
    align-items: center;
    justify-content: center;
    height: 100vh;
}
.calculator {

    box-shadow: var(--main-color) 1px 1px 1em;
    border-radius: 1em;
    height: fit-content;
    width: 370px;
    background-image: linear-gradient(-135deg,var(--secondary-color),var(--tertiary-color),var(--secondary-color));
    overflow: hidden;
}
.output {
    background-image: linear-gradient(-45deg,var(--main-color),var(--secondary-color));
    color: var(--tertiary-color);
    padding: 2em 0px;
}
.result,.calculation {
    display: flex;
    flex-direction: row-reverse;
    align-content: center;
    align-items: center;
    justify-content: end;
}
#result,#calculation {
    padding: 0.3em 10px;
    background-color: transparent;
    color: var(--light-color);
    border: none;
    text-align: right;
    font-size: inherit;
}
::placeholder {
  color: var(--light-color);
}
#result {
    font-size: 1.3em;
}
.result {
    height: 50px;
    font-size: 30px;
}
.calculation {
    height: 40px;
    font-size: 25px;
}
.keyboard {
    padding: 20px 10px;
    display: grid;
    grid-template-columns: auto auto auto auto;
    grid-template-rows: auto auto auto auto auto;
}
button {
    margin: 0.2em 0.2em;
    border: none;
    border-radius: 0.2em;
    height: 40px;
    opacity: 50%;
    color: var(--main-color);
    font-size: 15px;
    font-weight: bolder;
}
button:hover {
    background-image: linear-gradient(-45deg,var(--secondary-color),var(--tertiary-color),var(--secondary-color));
    color: var(--light-color);
    box-shadow: var(--main-color) 1px 1px 1em;
    transition-duration: 400ms;
}
button:active {
    background-image: linear-gradient(-45deg,var(--main-color),var(--secondary-color));
    color: var(--light-color);
    opacity: 100%;
    transition-duration: 400ms;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Calculator</title>
    <link rel="stylesheet" href="index.css" />
  </head>
  <body>
    <div class="calculator">
      <section class="output">
        <section class="result">
          <input id="result" placeholder="0" disabled />
        </section>
        <section class="calculation">
          <input id="calculation" disabled placeholder="0" />
        </section>
      </section>
      <section class="keyboard">
        <button id="clear">C</button>
        <button id="brackets">( )</button>
        <button id="percentage">%</button>
        <button id="divide">/</button>
        <button id="seven">7</button>
        <button id="eight">8</button>
        <button id="nine">9</button>
        <button id="multiply">X</button>
        <button id="four">4</button>
        <button id="five">5</button>
        <button id="six">6</button>
        <button id="subtract">-</button>
        <button id="one" class="getResult2">1</button>
        <button id="two">2</button>
        <button id="three">3</button>
        <button id="add">+</button>
        <button id="change-sign">+/-</button>
        <button id="zero">0</button>
        <button id="period">.</button>
        <button id="getResult">=</button>
      </section>
    </div>
    <script type="text/javascript" src="index.js"></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

How can I detect the @mouseup event in a Vue Bootstrap slider?

I have been using a vue-bootstrap slider that comes with two actions, @change and @update. My goal is to capture the final position of the slider once the movement ends. To achieve this, I decided to test both actions. In my scenario, @change triggers ev ...

Leverage Pinia store in Vue helper functions

I have been working on my Vue.js application and I am looking to implement some helper functions that will utilize a Pinia store within the app. These functions need to be accessible by multiple components. Should I define these helper functions directly ...

What is the best way to send multiple responses from an Express server using res.write and execute a specific action after each write operation?

I currently have an active express server that is sending data using res.write() Fetcher.js function fetcher() { console.log("fetcher function called") fetch('/units.html', { method: "POST", body: JSO ...

Having trouble with ion-item click not functioning in Ionic 3?

Working on my Ionic 3 project, I have encountered an issue with the ion-item click listener. The scenario is that I am adding text over a canvas and then attempting to change the style of the text (such as font-family, font-size, bold, and italic). The UI ...

Error in altering element width dimension

For my Bootstrap card project, I have some specific rules in mind: The card should have a minimum width of 250px (card #1 - looks good) If the first line exceeds 250px in length, the card should increase its width without wrapping the line (card #2 - widt ...

I have the ability to effectively open a modal whenever necessary, but I struggle with closing it afterwards

I've been working on implementing a React bootstrap modal, and while I can successfully open it when needed, I'm running into issues with closing it. I'm not sure what mistake I might be making. Here's my markup: <Modal show={this. ...

What is the best way to export OBJ files from Three.js geometry that has been manipulated by a GLSL shader?

I tried using a code snippet from Stack Overflow to export an OBJ file from geometry in a Three.js scene. The issue I'm facing is that the geometry, which has been displaced by a GLSL shader, does not seem to export with the displacement of vertices. ...

pressing a button unrelated to the 'close' button still triggers the close event

I have a notification bar that features a button in the center that links to another website. There is also a 'close' button on the far right. However, whenever I click the center button, it also triggers the close button. I tried moving the #cl ...

Is there a method to indicate type narrowing to TypeScript following an initial null/undefined validation?

After loading environment variables into my Node & Express app using 'dotenv', I take steps to ensure these values are present and of the correct type before starting the server. However, when attempting to use these variables later on, TypeScrip ...

Determine the status of the menu in React select by checking on key press events if it is open

In my project, I am utilizing react-select for the select elements. I'm curious if there's a way to detect the "open" or "closed" state of the menu through a keydown event in the select (either on the select input or within the menu). The versi ...

Update state within React components without impacting any other state variables

Imagine I have an object structured like this: person : { name : "Test", surname : "Test", age : 40, salary : 5000 currency : "dollar", currency_sign : "$", . . . } I am looking to achieve the following I will make ...

The justify-content-sm-center behavior in Bootstrap seems to be malfunctioning

I am facing an issue with justify-content-sm-center in Bootstrap 5. It is not functioning as intended when trying to center a specific div on smaller screens (below 578px). I have applied the justify-content-sm-center class to the div, but it does not work ...

Saving data values for utilization in jQuery

Recently, I've come across a series of links structured like this: <a class="colorBox" href="#" title="#0676B3"></a> <a ... <a ... these links all have color values in the title attribute <a ... What I'm trying to do is uti ...

What is the best way to send information from server-side code to an EJS template?

I am facing an issue with retrieving data from my simple server for an ejs template. While I can successfully get the data through the URL in my browser, I am struggling to pass it to the template. This is my data retrieval method: app.get('/some&ap ...

Disable mandatory checkbox with jQuery validator extension

Check out this test form I created here: Here is the code for the checkboxes: <div class="optIn"> <div id="line1"> <div class="checkbox"><input type="checkbox" checked="checked" value="true" name="MailingListOptIn"> ...

Reload the text content of a locally hosted webpage within an iframe at regular intervals

I have set up a simple webpage on my local machine to showcase the contents of some text files on a dedicated monitor. However, I am facing an issue where refreshing the entire webpage causes flickering. My goal is to only refresh the iframes and reload t ...

Navigating Successful or Unsuccessful Payment Routing within the Razorpay System

Recently started exploring Payment Gateway Integration and need assistance. I am looking for guidance on redirecting a URL after successful or failed payments in Razorpay. I need JavaScript code for this purpose. I believe the handler function can be util ...

Trouble with Javascript slideshow: Incorrect display and malfunctioning

Struggling with implementing a slideshow banner on my webpage, despite following the W3 tutorial. Here is the code I am currently using: HTML: <div class="slide-content" style="max-width:1000px"> <img class="slidepic" src="testheadphoto.jpg" st ...

Is there a way for me to ensure that a response is only returned once a method call has been completed in

Seeking assistance with a Node.js application using Express. I am trying to create a REST endpoint that returns the response of an HTTP call. However, no matter what I attempt, it always returns before the HTTP request has completed. Can anyone provide g ...

I can't understand why this question continues to linger, I just want to remove it

Is there a valid reason for this question to persist? I'm considering removing it. ...