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

The console is displaying an undefined error for _co.photo, but the code is functioning properly without any issues

I am facing an issue with an Angular component. When I create my component with a selector, it functions as expected: it executes the httpget and renders a photo with a title. However, I am receiving two errors in the console: ERROR TypeError: "_co.photo ...

Placing information within a nested array with multiple levels of nesting

I'll try to keep this concise, Here is the structure of the schema... import mongoose from 'mongoose' const QuestionSchema = mongoose.Schema({ questionTitle: { type: String, required: " title"}, questionBody: { type: Stri ...

Display words on screen and then alter hue using HTML and CSS

Is there a way to dynamically change the color of text inside <a> tags from black to red after a specific time interval and keep it permanently red? do { document.getElementById("code").innerHTML +="<a>Hello World</a><br>"; awa ...

The property cannot be set for an undefined element in Jquery UI slider tabs

There seems to be some extra space at the bottom of the slider tabs between the navigators and content. Additionally, I am facing a challenge in making the page responsive as the content size does not adjust when I resize the window. To see the changes, I ...

Apply the style when the page loads and remove it when clicked

There is a feature in my code that adds a class when an element with the class .tab is clicked. $(function() { $(".tab").click(function() { $(this).addClass('blueback'); $(".tab").not($(this)).removeClass('bl ...

What is the process for importing an md file in a create-react-app project using JavaScript?

Attempting to execute the blog example provided on Material UI's getting started page. However, encountering an issue with the source code: Inside blog.js import post1 from './blog-post.1.md'; . . . return( <Main>{post1}<Main/> ...

Obtain the model value using Yii jQuery and then proceed to submit the form

Within the _form.php view, there is a presence of $model and a CActiveForm $form. I implemented JavaScript code to compare the value of $model->publication_date with the current date. If they are identical, the form will be submitted automatically. Othe ...

How to invoke a function in an isolated scope of AngularJS using JavaScript

We are in the process of gradually switching our application to work with Angular. I have developed an angular module and a directive that aims to connect specific functionality to an HTML element. angular.module('myApp', [ ]) .controller(&ap ...

Utilizing a plugin to execute a function in Wordpress

I'm currently facing the challenge of combining two WordPress plugins without the need to modify one to fit into the other seamlessly. My main question is: How can I call a function from one plugin that exists outside of another plugin? For example, ...

Utilizing Mantine dropzone in conjunction with React Hook Form within a Javascript environment

Can Mantine dropzone be used with React hook form in JavaScript? I am currently working on a modal Upload using Tailwind components like this import { useForm } from 'react-hook-form'; import { Group, Text, useMantineTheme } from '@mantine/c ...

Discover the identity of an element through the value of another element

Looking for a way to retrieve the id value based on the input value in this HTML code. For instance, I need to identify the id value associated with the input value of number2 - which is unknown2. How can this be achieved using jQuery? <th id="unknow ...

Can you tell me what this code on Facebook is for?

Upon inspection of Facebook's activity in my browser, I stumbled upon the following code snippet: for (;;);{"t":"refresh"} Attempting to decipher its purpose reveals an infinite loop. Can you identify its function? ...

Integrating various object properties in Angular's select ng-options: A comprehensive guide

I need to merge text and number properties from JSON to display as select options values by default. The expected output should be: 000.000.0001 - Chicago HTML: <!doctype html> <html ng-app="plunker" > <head> <meta charset="utf-8"& ...

Python Selenium error: NoSuchElementException - Unable to find the specified element

Coding Journey: With limited coding knowledge, I've attempted to learn through various resources without much success. Now, I'm taking a different approach by working on a project idea directly. The goal is to create a program that interacts wi ...

The directive attribute in AngularJS fails to connect to the directive scope

I have been attempting to pass an argument to a directive through element attributes as shown in the snippet below: directive app.directive('bgFluct', function(){ var _ = {}; _.scope = { data: "@ngData" } _.link = function(scope, el ...

Comparing Embedded and Linked JS/CSS

In my experience, I understand the advantages of using linked CSS over embedded and inline styles for better maintainability and modularity. However, I have come across information suggesting that in certain mobile web development applications, it may be m ...

I'm having trouble getting jQuery to work properly with Bootstrap buttons

In simple terms, my objective is to have two buttons on a page where "1" is displayed when the first button is pressed and "2" is displayed when the second button is pressed. This functionality works fine with radio inputs, but when I incorporate button la ...

Having trouble with loading JavaScript during ng build --prod process

The JavaScript file I'm using for multiple emails (multiple_emails.js plugin) works well with ng serve. Here is my code: (function( $ ){ $.fn.multiple_emails = function(options) { // Default options var defaults = { ...

Creating a table from data in your database using Firebase

Can anyone guide me on how to craft a data table similar to this examplehttps://i.sstatic.net/xiUNn.pngusing information from a Firebase database like shown here https://i.sstatic.net/YBzjz.png The table should have columns for ID, Title, Number of Answer ...

Organize tabs with ease in the bootstrap-tabdrop plugin

My webpage features a navigation bar along with the bootstrap-tabdrop plugin, which places tabs in a dropdown menu if there are too many to display on one line. The main objective is: No action when navigating through currently displayed tabs. Clicking o ...