Tips for dynamically updating values when input numbers are modified using JavaScript

Check out this amazing tip calculator on netlify. I successfully built it using html, scss, and javascript without relying on any tutorials. Despite taking longer than expected due to being a beginner, I am proud of the outcome.

Now, I need some assistance with a specific function.

I want the numbers in the calculator to automatically update when I enter a new dollar amount in the billing input field.

For example, if the bill is $50 and the tip percentage is 50%, the tip amount should be $25 making the total bill $75.

If I accidentally change the bill amount to $60, the tip amount should adjust to $30, resulting in a total bill of $90. However, I'm struggling to make these updates happen instantly when modifying the dollar amount in the billing input field.

I suspect that utilizing a "change" event listener might solve this issue, but I'm uncertain about how to best incorporate it or if it's the correct approach.

// Upper Box Selections

const tipPercent = document.querySelector(".tip-percent");
const tipSlider = document.querySelector("#tip-slider");

tipSlider.oninput = function () {
    ...
};

// Bottom Box Selections

const splitSlider = document.querySelector("#split-slider");

splitSlider.oninput = function () {
    ...
};

Seeking guidance on improving this functionality? Visit .

Answer №1

To ensure that the function is executed each time there is an input for both the bill and tip, it's recommended to name the function something like calcTotal():

const tipPercent = document.querySelector(".tip-percent");
const tipSlider = document.querySelector("#tip-slider");

function calcTotal() {
    let billInput = Number(document.querySelector("#bill-amt").value);
    tipPercent.innerHTML = this.value + "%";

    // Noticed that number input type still returns a string
    // You can wrap multiple variables in parenthesis to append methods
    let tipAmount = document.querySelector(".tip-amount");
    // If a variable is referenced but not defined, it will be added to the window element - now usable in another function
    let tipTotal = Number((billInput * Number(this.value / 100)).toFixed(2));

    tipAmount.innerHTML = "$" + tipTotal.toFixed(2);

    const billTotal = document.querySelector(".bill-total");

    billForSplit = Number(billInput + tipTotal).toFixed(2);

    billTotal.innerHTML =
        "<strong>$</strong>" + "<strong>" + billForSplit + "</strong>";
};
tipSlider.oninput = calcTotal;
document.querySelector("#bill-amt").oninput = calcTotal;

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

Error: Unable to access the 'name' property of an undefined variable

When running the code, I encountered a "TypeError: Cannot read property 'name' of undefined" error, even though when I console.log it, it provides me with the object import React from "react"; class Random extends React.Component { constructo ...

Press the button to execute the PHP function seamlessly without the need to refresh the page

Is there a way to create buttons "a" and "b" that can execute a function without causing the page to refresh? The challenge I'm facing is that when I call this function in "index.php" or any other page, it automatically runs as soon as the page loads ...

The absence of a semi-colon in JSLint

I encountered an error message indicating a semicolon is missing, however I am unsure of where to place it. Here is the snippet of code: $('.animation1').delay(350).queue(function(){ $(this).addClass("animate-from-top") }); ...

What is the best way to create a button with a dynamic background animation in React?

Looking to design a button with an animated background, possibly in gif or video format. An example of what I have in mind is the DOWNLOAD button on this website's main page: Ideally, I am hoping for a solution using React. ...

Executing a function following the removal of an element

I am trying to remove an element after exiting a jQuery dialog. I have used the .remove() function, but the element is not accessible after executing .remove(). How can I "destroy" an object in JavaScript and allow it to be called again without refreshing ...

Tips for seamlessly incorporating WalletConnect into your decentralized app with the help of web3-react

I have been working on integrating WalletConnect into my project by referring to the documentation provided by web3-react. The configuration settings I am using for the connector are as follows: import { WalletConnectConnector } from '@web3-react/wal ...

Navigate within the div by scrolling in increments of 100%

I am facing an issue with a div that contains multiple children set to 100% height. My goal is to scroll exactly the height of one child (which is also 100%) on each scroll. However, I am struggling to prevent scrolling multiple steps at a time. I have tri ...

Ways to retrieve the initial key object received through an AJAX request

I have a form with three dynamic dropdowns. The second dropdown depends on the first one, and the third dropdown depends on the second one. Therefore, selecting an option in the first dropdown will automatically populate the next two dropdowns. Below is t ...

Displaying Vue.js tooltips in a table when the text gets clipped

I'm currently facing an issue with creating a tooltip in my vue.js document. I attempted to follow this guide from https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_tooltip in order to create one, but it's not working as expected. Her ...

Calculate the sum of multiple user-selected items in an array to display the total (using Angular)

Within my project, specifically in summary.component.ts, I have two arrays that are interdependent: state: State[] city: City[] selection: number[] = number The state.ts class looks like this: id: number name: string And the city.ts class is defined as f ...

Update data in PHP dynamically without reloading the page

It would be great if they are doing well! I have encountered a minor issue - everything seems to work perfectly, but it doesn't quite meet my requirements. I am referring to this particular function: <script> var previous = null; var current = ...

Can we utilize object properties in this manner?

Hey there! I've been experimenting with the react-bootstrap library recently, trying to get better at using it. While going through the tutorial, I came across some ES6 code that caught my attention. function FieldGroup({ id, label, help, ...props } ...

Using TypeScript with Node.js and Sequelize - the process of converting a value to a number and then back to a string within a map function using the OR

Currently, I am facing a challenge in performing addition on currency prices stored as an array of objects. The issue arises from the fact that the currency type can vary among 3 different types within the array of objects. The main hurdle I encounter is ...

Encountering an issue in Next.js when using getStaticProps: reading 'map' of undefined properties

The Image above shows the error and the code I have attempted.Server Error TypeError: Cannot read properties of undefined (reading 'map') This particular error occurred during the page generation process. Any console logs will appear in the term ...

Vue.js is displaying an error message stating that the data property is

I am struggling to access my data property within my Vue.js component. It seems like I might be overlooking something obvious. Below is a condensed version of my code. The file StoreFilter.vue serves as a wrapper for the library matfish2/vue-tables-2. &l ...

The tablesorter plugin from Jquery isn't functioning properly on my dynamically loaded ajax table

I am having trouble getting Tablesorter to work with my table. I attempted to use .trigger('update') but it did not have the desired effect for me. Instead, I tried using stupidtable and it worked to some extent, but not perfectly (it did not sor ...

Check if the browser is compatible with the FREEZE and RESUME lifecycle events

Is there a method to determine if a browser is capable of registering the freeze and resume lifecycle events? Even after checking with Modernizr, a reliable JS library, it appears that these events are not supported. Although extremely beneficial, Safari ...

Determine the total of the final column in recently added rows by utilizing JavaScript

I have a table where users can dynamically add rows as needed. I am looking to implement a feature that will display the total of the last column in a text box underneath the table using JavaScript. If real-time calculations are not feasible, then I am ope ...

Is it possible for the connectedCallback() method within a Custom Component to have varying interpretations based on the specific context in which it is implemented?

I have recently developed a Custom Component that incorporates a Vue instance: class ContentCardExample extends HTMLElement { connectedCallback() { const card = document.createElement('div'); card.setAttribute("id", "app") card.i ...

In JavaScript, the addition and subtraction buttons may become disabled after nested lists are used

Recently, I embarked on a project to enhance the functionality of restaurant table items and implement value-saving features. Initially, everything worked smoothly with one item list. However, upon introducing a second list and attempting to manipulate it ...