Determine the overall cost based on varying percentage increases for each step

I am currently working on developing a price estimation calculator.

Here is the breakdown:

For 1000 MTU, the price will be 0.035, resulting in a total of 35. For 2000 MTU, the price will be 0.034, making the total 67. For 3000 MTU, the price will be 0.0329, with a total of 98.79.

And so forth...

I tried implementing the following code but encountered a NaN error.

Any new suggestions on how to write more efficient code would be greatly appreciated.

<p id= "rangeValue" >

</p>
<div class="range-wrap">
        <div class="range-value" id="rangeV"></div>
<input id="myinput" type="range" name="points" min="1000" max="100000" value="1000" oninput="rangeValue.innerText = this.value" >
</div> 
const slider = document.getElementById("myinput")
const min = slider.min
const max = slider.max
const value = slider.value

slider.style.background = `linear-gradient(to right, #0080FF 0%, #0080FF ${(value-min)/(max-min)*100}%, #596680 ${(value-min)/(max-min)*100}%, #596680 100%)`

slider.oninput = function() {
  this.style.background = `linear-gradient(to right, #0080FF 0%, #0080FF ${(this.value-this.min)/(this.max-this.min)*100}%, #596680 ${(this.value-this.min)/(this.max-this.min)*100}%, #596680 100%)`
};


// Add a change event listener to the range slider
   slider.addEventListener('change', function() {
  // Get the value of the range slider
  var value = this.value;
  var container = document.querySelector('#rangeValue');
  
  let cost;
  function calculateCost(value) {
  if (value === 1000) {
    cost = 0.0350;
  } else if (value === 2000) {
    cost = 0.0340;
  } else {
    cost = 0;
  }
  return cost;
}
var totval=value * cost;
totval = totval.toFixed(2);
  
  container.innerHTML = totval;
  // Print the value to the console
 // console.log(value);
});

const
    range = document.getElementById('myinput'),
    rangeV = document.getElementById('rangeV'),
    setValue = ()=>{
        const
            newValue = Number( (range.value - range.min) * 100 / (range.max - range.min) ),
            newPosition = 10 - (newValue * 0.2);
        rangeV.innerHTML = `<span>${range.value}</span>`;
        rangeV.style.left = `calc(${newValue}% + (${newPosition}px))`;
    };
document.addEventListener("DOMContentLoaded", setValue);
range.addEventListener('input', setValue);
#myinput {
  border-radius: 8px;
  height: 8px;
  width: 100%;
  outline: none;
  -webkit-appearance: none;
}

input[type='range']::-webkit-slider-thumb {

  -webkit-appearance: none;
   width: 20px;
  height: 20px;
  border-radius: 50%;
   background: #0080FF;
}


.range-wrap{
    width: 500px;
    position: relative;
}
.range-value{
    position: absolute;
    top: 150%;
}
.range-value span{
    width: 30px;
    height: 24px;
    line-height: 24px;
    text-align: center;
    background: transparent;
    color: #0A0E1C;
    font-size: 20px;
    display: block;
    position: absolute;
    left: 50%;
    transform: translate(-50%, 0);
    border-radius: 6px;
}
.range-value span:before{
    content: "";
    position: absolute;
    width: 0;
    height: 0;
    top: 100%;
    left: 50%;
    margin-left: -5px;
    margin-top: -1px;
} 

Answer №1

To convert the input value from a string to an integer, you can use the `parseInt()` function. This will allow you to accurately calculate your prices. Additionally, ensure that the `calculateCost()` function is correctly utilized within your event listener. Here is the updated code:

const slider = document.getElementById("myinput")
const min = parseInt(slider.min)
const max = parseInt(slider.max)
const value = parseInt(slider.value)

slider.style.background = `linear-gradient(to right, #0080FF 0%, #0080FF ${(value-min)/(max-min)*100}%, #596680 ${(value-min)/(max-min)*100}%, #596680 100%)`

slider.oninput = function() {
  this.style.background = `linear-gradient(to right, #0080FF 0%, #0080FF ${(this.value-this.min)/(this.max-this.min)*100}%, #596680 ${(this.value-this.min)/(this.max-this.min)*100}%, #596680 100%)`
};


// Add a change event listener to the range slider
slider.addEventListener('change', function() {
  // Get the value of the range slider
  var value = parseInt(this.value);
  var container = document.querySelector('#rangeValue');

  let cost;
    if (value === 1000) {
      cost = 0.0350;
    } else if (value === 2000) {
      cost = 0.0340;
    } else {
      cost = 0;
    }
  var totval=value * cost;
  totval = totval.toFixed(2);

  container.innerHTML = totval;
});

const
    range = document.getElementById('myinput'),
    rangeV = document.getElementById('rangeV'),
    setValue = ()=>{
        const
            newValue = Number( (range.value - range.min) * 100 / (range.max - range.min) ),
            newPosition = 10 - (newValue * 0.2);
        rangeV.innerHTML = `<span>${range.value}</span>`;
        rangeV.style.left = `calc(${newValue}% + (${newPosition}px))`;
    };
document.addEventListener("DOMContentLoaded", setValue);
range.addEventListener('input', setValue);
#myinput {
  border-radius: 8px;
  height: 8px;
  width: 100%;
  outline: none;
  -webkit-appearance: none;
}

input[type='range']::-webkit-slider-thumb {

  -webkit-appearance: none;
   width: 20px;
  height: 20px;
  border-radius: 50%;
   background: #0080FF;
}


.range-wrap{
    width: 500px;
    position: relative;
}
.range-value{
    position: absolute;
    top: 150%;
}
.range-value span{
    width: 30px;
    height: 24px;
    line-height: 24px;
    text-align: center;
    background: transparent;
    color: #0A0E1C;
    font-size: 20px;
    display: block;
    position: absolute;
    left: 50%;
    transform: translate(-50%, 0);
    border-radius: 6px;
}
.range-value span:before{
    content: "";
    position: absolute;
    width: 0;
    height: 0;
    top: 100%;
    left: 50%;
    margin-left: -5px;
    margin-top: -1px;
}
<p id= "rangeValue" >
</p>
<div class="range-wrap">
<div class="range-value" id="rangeV"></div>
<input id="myinput" type="range" name="points" min="1000" max="100000" value="1000" oninput="rangeValue.innerText = this.value" >
</div> 

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

What is the accurate Scrapy XPath for identifying <p> elements that are mistakenly nested within <h> tags?

I am currently in the process of setting up my initial Scrapy Spider, and I'm encountering some challenges with utilizing xpath to extract specific elements. My focus lies on (which is a Chinese website akin to Box Office Mojo). Extracting the Chine ...

What is the reason for jQuery's inability to recognize ":not(#menu *)" in a selector?

I have created a Javascript-based navigation bar that is triggered by clicks instead of hover for better mobile usability. I have made sure to keep the HTML, CSS, and JavaScript code as simple as possible. To ensure that clicking anywhere outside the menu ...

Issue encountered in Wicket Ajax Error Log: ERROR: The listener for the "click" event cannot be bound to the "AjaxCheckBox" element as it is not present in the Document Object Model (DOM)

When running my program, I am trying to dynamically add Panels to the main page and utilize "setVisible(boolean)" functionality. However, I am encountering an error: ERROR: Cannot bind a listener for event "click" on element "institutCheck7" because the ...

Issue with displaying marker information on Angular Google Maps

https://i.stack.imgur.com/qUyRo.png I'm in a bit of a pickle trying to figure out how to properly display the information when clicking on a marker. I attempted to include $scope.info in the onClick function, but it still refuses to show up. Could s ...

Learn how to display two rows of div elements within a single div container

In my program, I am using a for loop to display multiple div elements in one row. The first div is showing up correctly, but I am having trouble inserting a new div that looks the same as the first one. How can I achieve this? Thank you in advance. "first ...

Expanding Nested Resources with Rails and JQUERY Toggling

I'm currently facing a challenge with toggling a "finish" action involving nested resources in rails. I've been struggling to make it work as intended and keep receiving the 'Couldn't find List without an ID' error. While I underst ...

Having trouble with React JS BrowserRouter not routing correctly when used with Express JS and Nginx proxy

I am facing an issue where I need to send parameters to a React component through the URL. This works perfectly fine when I test it in my localhost development environment. However, the problem arises when I deploy the React app to my live server (). The ...

"Utilize Bootstrap Modal to load dynamic content with Ajax and incorporate loading

When I use the Bootstrap Modal to load content from another page, the data is quite complex with multiple queries and dynamic forms. As a result, when the modal opens, it tends to get stuck momentarily. I am looking for some sort of animation or indicator ...

Unusual behavior involving the selection of $stateParams

Seeking a solution for updating angular-ui route parameters based on select field changes. Issue: The route successfully updates with the selected parameter, but the select field does not reflect the change in option selection. Check out the Plunkr. Clic ...

Error encountered: Attempting to access the 'length' property of an undefined variable in JSON data while using the $.each function

When I execute the following code snippet: var obj = $.parseJSON(json.responseText); $.each(obj.collection.response, function (i) { $.each(this.PRESENT_STUDENT, function (i, j) { $.each(j , function (i, j){ $( ...

What steps can I take to resolve the "this is undefined" issue in VueJS?

Whenever I include the line this.$store.commit('disconnect');, it throws a "this is undefined" error. Any suggestions on how to resolve this issue? store/index.js : export const state = () => ({ log: false, user: {token: null, id: null, u ...

Conceal the standard style class of the p:selectOneRadio element

On my xhtml page, I've implemented p:selectOneRadio. However, I'm struggling to remove the default style class .ui-helper-hidden-accessible, resulting in the radio button icons not being visible. Here's a snippet of my code: <p:selectOne ...

NodeJS: Retrieve Over 10,000 Images From the Server

Attempting to retrieve over 10,000 images from a server led me to create this script: const http = require('http') const fs = require('fs') const opt = { agent: new http.Agent({ keepAlive: true, maxSockets: 5 }), headers ...

Transmitting HTML5 application settings via URL

I am interested in creating an HTML5 app that utilizes the WebAudio API. This app will allow users to customize certain parameters. Users should be able to 'share' these settings by sending a share URL, which can be clicked by others to view the ...

Struggling to retrieve an integer value from user input?

Hey there! I am facing an issue where I receive data from a form via POST, and some fields need to be treated as integers. However, when I use: var_dump($_POST) All the data is returned as strings enclosed in double quotes, which I would like to remove. ...

How to address hover problems in D3.js when dealing with Path elements and updating tooltip information after brushing the focus

Seeking assistance with a Multi Series, Focus + Context D3 chart and hoping to address my main queries all at once. The questions that need resolving are: How can I prevent the tooltips I've generated from being affected by the hair-line (which t ...

Wavesurfer encounters difficulty generating waves due to a CROS Error caused by cookie settings

When using wavesurfer, an error occurs that states: XMLHttpRequest cannot load https://audiotemp.domain.net/RE65bbf6f0a2760184ab08b3fbf9f1d249.mp3. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http ...

I'm not skilled in programming, so I'm not sure what the problem is with the code

While working on my Blogger blog, I encountered the need to add a fixed sidebar ad widget that would float along the screen. After trying multiple codes, I finally found one that worked. However, using the template's built-in variable functions led to ...

What steps can I take to rearrange my return statement within an asynchronous function?

Imagine having a function that fetches data from a database. findById(id) { return Model.findById(id) } The goal is to rearrange the output from the user data in this format: { name: "Tom", age: 57 } To something like this: { message: ...

Hovering over objects in Three.js does not function as effectively as clicking on them

Just getting into Three.js I'm attempting to load a GLTF model and add mouseover and mouseout events. The goal is for the color of the GLTF model to change on mouseover and revert back to the original on mouseout. I have had some success with this, ...