Determine total and showcase it as the range slider is adjusted

Seeking to calculate and present the result of three range sliders. The equation I aim to showcase is:

KM driven per year * Avg KM/100L / Price of fuel

I have managed to display each slider's individual values, but I am uncertain about how to show the calculation.

View Codepen

<div>
  <p>KM Driven per Year</p>
  <p id="myAvgKM"></p>
  <input type="range" min="0" max="300000" value="80000" step="1000" class="slider" id="kmdriven">

  <p>On average, my truck gets around:</p>
    <div class="response-container">
      <p id="myAvgKPL"></p>
      <p>L/100KM</p>
    </div>
  <input type="range" min="4" max="60" value="40" id="avgkm">

  <p>Diesel prices are usually:</p>
  <p id="price"></p>
  <input type="range" min="0.000" max="3.000" value="1.308" step=".001" id="priceValue">
</div>

<div>
  <p>In the first year alone, our offerings would save you:</p>
  <p id="savings"></p>
</div>

function calculate () {
// Display KM Driven Slider
var kmPerYear = document.getElementById("kmdriven")
var kmOutput = document.getElementById("myAvgKM")
kmOutput.innerHTML = kmPerYear.value;

kmPerYear.oninput = function() {
  kmOutput.innerHTML = this.value;
}

// Display Avg Mileage
var avgKM = document.getElementById("avgkm")
var avgKMOutput = document.getElementById("myAvgKPL")
avgKMOutput.innerHTML = avgKM.value;

avgKM.oninput = function() {
  avgKMOutput.innerHTML = this.value;
}

//Display Avg Price
var avgPrice = document.getElementById("priceValue")
var priceOutput = document.getElementById("price")
priceOutput.innerHTML = avgPrice.value;

avgPrice.oninput = function () {
  priceOutput.innerHTML = this.value;
}

// The Calculations!


  document.getElementById("savings").innerHTML = "$ ";

}

Answer №1

To link your function to the onchange event, use the following code:

<input onchange="calculate()" type="range" min="0" max="300000" value="80000" step="1000" class="slider" id="kmdriven">

Delete the oninput attribute as your slider does not support it, and replace it with onchange.

Include the formula for calculating total savings:

var total = (kmPerYear.value / 100) * (avgKM.value * 1.2) * avgPrice.value;

document.getElementById("savings").innerHTML = `$ ${total}`;

function calculate () {
// Display KM Driven Slider
var kmPerYear = document.getElementById("kmdriven");
var kmOutput = document.getElementById("myAvgKM")
kmOutput.innerHTML = kmPerYear.value;

// Display Avg Mileage
var avgKM = document.getElementById("avgkm")
var avgKMOutput = document.getElementById("myAvgKPL")
avgKMOutput.innerHTML = avgKM.value;


//Display Avg Price
var avgPrice = document.getElementById("priceValue")
var priceOutput = document.getElementById("price")
priceOutput.innerHTML = avgPrice.value;

// The Math!
var total = (kmPerYear.value / 100) * (avgKM.value * 1.2) * avgPrice.value;
  
  document.getElementById("savings").innerHTML = `$ ${total}`;
  
}
.response-container {
  display: flex;
}

   
<div>
  <p>KM Driven per Year</p>
  <p id="myAvgKM"></p>
  <input onchange="calculate()" type="range" min="0" max="300000" value="80000" step="1000" class="slider" id="kmdriven">
  
  <p>On average, my truck gets around:</p>
    <div class="response-container">
      <p id="myAvgKPL"></p>
      <p>L/100KM</p>
    </div>
  <input  onchange="calculate()"  type="range" min="4" max="60" value="40" id="avgkm">
  
  <p>Diesel prices are usually:</p>
  <p id="price"></p>
  <input  onchange="calculate()"  type="range" min="0.000" max="3.000" value="1.308" step=".001" id="priceValue">
</div>

<div>
  <p>In the first year alone, our services would save you:</p>
  <p id="savings"></p>
</div>

Answer №2

Make sure to place the window onload script at the bottom of your javascript file window.onload=calculate;

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

Adding a script to the head of a Next.js page by using the Script component

I need assistance with inserting tracking code from Zoho application into the Head section of each page in my Next.js application. I am currently using a _document.tsx file and following the instructions provided by Next.js regarding the use of the Next.js ...

Utilizing various filters and sorting options on API response within Angular 8

Upon receiving the following API response: [ { "imgPaths":[ "gallery/products/55ccb60cddb4d9bded02accb26827ce4" ], "_id":"5f3e961d65c6d591ba04f3d3", "productName":" ...

Looping through values in VueJS from 100 to 0

I am currently working on creating a power meter that will smoothly transition from 100 to 0 and back again to 100. The idea is for the user to press a button, causing the meter to stop at a random value. I just need some assistance in getting the loop fu ...

Using JavaScript to insert a value through AJAX

I'm currently working on a website that displays the value of a .TXT file, and here is the progress I've made so far: <script> $(document).ready(function() { $("#responsecontainer").load("info.txt"); var refreshId = setInterval(function( ...

(MUI Textfield) Error: Unable to access properties of undefined (specifically 'focus')

I have been working with the useRef hook in my Material Ui Textfield and have encountered the error Uncaught TypeError: Cannot read properties of undefined (reading 'focus'). I am unsure how to resolve this issue. Here is my current code snippet: ...

`Next.js project experiencing issues with scroll trigger functionality`

I've been working on a gsap animation with a scroll trigger, and while the animation itself functions fine, it's not triggering as expected. The AnimationEffect code involves using gsap and scrolltrigger to create the animation. The Hero section ...

Toggle the Editable Feature in AngularJS JSON Editor

Currently, I'm utilizing a library called ng-jsoneditor that is available on GitHub. I am attempting to switch the state of an element from being editable to being read-only. To indicate that an element should be read-only, I need to specify the onE ...

Troubleshooting a dysfunctional collapsed navbar in React with Bootstrap 5

I am experiencing an issue where the collapsed navbar icon does not expand when clicked on smaller screens. I followed the example provided by bootstrap 5 and made sure to include bootstrap css/js and jquery. class CustomNavBar extends Component { re ...

Error: Unable to locate module './clock' in the directory '/home/n/MyWork/my-app/src'

Upon attempting to start up the project, I encountered an error message stating: "Module not found: Can't resolve './clock' in '/home/n/MyWork/my-app/src'" The structure of the project is as follows: My-app --node-modules --public ...

How can I designate the file name when using Ajax to export in Excel formatting?

Can you help me with the code to set a specific filename for downloading an Excel file? if(comp_id != "Select Company") { $.ajax({ url: 'includes/export.php', data: { action: 'compreport', 'comp':comp_i ...

Guide on transforming 3D obj files into particles using three.js

I've been experimenting with particles in three.js, but I've encountered an issue when trying to convert an obj file (3D model) into particles. Here are the code snippets I've been working with, but so far all my attempts have failed. Does ...

Why am I receiving an undefined value when I try to log the createdAnimal?

My main goal with this code is to successfully console.log(createdAnimal) and have the objectAnimal with specific parameters printed out. The following code snippet demonstrates the desired parameters: animalMaker('cat','flying',true); ...

Updating Tailwind CSS to accommodate older web browsers by converting modern rgba() notation to be browser-compatible

I am facing a challenge with Tailwind CSS v3+ as it builds colors into the rgb space/color notation that is not compatible with an older browser (Safari 11) that my web app now needs to support. For example, rgb(163 160 158 / var(--tw-bg-opacity) The iss ...

Encountering Issues with NextJS Dynamic SSR: Mobile Devices stuck on loading screen

Issue: The dynamic import feature of Next JS is encountering loading issues specifically on mobile browsers such as Google Chrome and Safari on IOS. Strangely, the functionality works smoothly on desktop browsers like Google Chrome and Mozilla. The projec ...

How to transform a file into a uInt8Array using Angular

Looking to implement a feature where I can easily upload files from Angular to PostgreSQL using a Golang API. In my Angular component, I need to convert my file into a uInt8Array. I have managed to convert the array, but it seems to be encapsulated in som ...

Activate the text area message by clicking on the href link

I am currently working on customizing the intercom plugin for a WordPress site. My goal is to have a message triggered when a user clicks on a hyperlink, essentially simulating the enter key press in a textarea. Here is the code snippet that I am using: ...

What are the drawbacks of relying on a dependent dependency in software development?

In a recent discussion on Stack Overflow, it was suggested that the best practice is to install packages from sub-dependencies for future use in the app, rather than directly from the dependencies node_modules folder. However, my scenario is a bit unique. ...

Creating a topographical map from a 3D model

<!--B"H--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Custom Terrain Heightmap Generator</title> ...

Tips for managing the background color of a box when the function is constantly refreshing in Internet Explorer

function process(Objects) { var objectId = Objects; displayContent(objectId); } function displayContent(objectId) { var boxId = objectId.id; var color = ret ...

How to Handle an Empty Route with a Trailing Slash in Backbone Routing?

While I am aware of the potential SEO issues that come with duplicate content, my project is not currently focused on that aspect. Looking at my backbone router configuration, here it is: routes: { "": "startOrder", "order/:orderNumber/:stepName" ...