JavaScript conditional calculation mechanism

Here is the code snippet I am referring to:

function myFunction() {
    var x = document.getElementById("ins-feet").value;

    if(x >= 0 && x <= 1499) {
        document.getElementById("show-cost").innerHTML = "Cost: $" + 300;
    } else if(x >= 1500 && x <= 1999) {
        document.getElementById("show-cost").innerHTML = "Cost: $" + 320;
    } else if(x >= 2000 && x <= 2500) {
        document.getElementById("show-cost").innerHTML = "Cost: $" + 340;
    } else if(x > 2500) {
        var additionalCost = (x - 2500) * 0.10;
        document.getElementById("show-cost").innerHTML = "Cost: $" + (340 + additionalCost);
    }

}

I need help with the last line. When x is greater than 2500, the "show-cost" will display 340 plus an additional 0.10 for every increment. For example, if x > 2501, the cost would be 340.1, and for x > 2502, the cost would be 340.2, and so on.

Answer №1

It's not as complicated as it seems:

First, find the difference between x and 2500, then perform a simple subtraction.

Next, multiply 0.1 by that difference, like this:

340 + 0.1 * (x - 2500)

To avoid any concatenation issues, make sure to enclose it in parentheses:

"Cost: $" + (340 + 0.1 * (x - 2500))

Your function should look like this:

function calculateCost() {
    var x = document.getElementById("ins-feet").value;

    if(x>=0 && x<=1499) {
        document.getElementById("show-cost").innerHTML = "Cost: $" + 300;
    } else if(x>=1500 && x<=1999) {
        document.getElementById("show-cost").innerHTML = "Cost: $" + 320;
    } else if(x>=2000 && x<=2500) {
        document.getElementById("show-cost").innerHTML = "Cost: $" + 340;
    } else if(x>2500) {
        document.getElementById("show-cost").innerHTML = "Cost: $" + (340 + 0.1 * (x - 2500));
    }

}

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

Implementing automatic pagination based on container height using jQuery

Looking to convert an AngularJS fiddle into jQuery. The goal is to create pagination using several p tags only with jQuery. Current code: <div class="parent"> <p>text1</p> <p>text2</p> <p>text3</p> ...

Instead of adding a new object to the array, consider increasing the quantity of an existing object

I am new to working with a shopping cart component and my code is structured like this: let cartCount = document.getElementById("counter"); let isItemSelected = false; let itemCount = 0; let shoppingCart = []; let selectedSize = ""; let displaySelectedSiz ...

Reset the dropdown list back to its initial state

I am facing an issue with two dropdown lists in my view. When I change the value on the first one, it should update the second one accordingly. Initially, this functionality works fine with the script provided below. However, if I change the first dropdown ...

Locate a piece of text with jQuery and enclose it within a specified container

Check out this code <form method="get" name="form_delivery"> Pick the country where you want your delivery<br> <select name="deliverymethod"> <option value="0" selected="selected">Choose a country / region</option> ...

What steps can be taken to effectively build a test suite architecture using Jest?

After exploring all the available resources on the Jest documentation website, including various guides and examples, I have yet to find a solution to my specific question. I am in search of a methodology that would enable me to individually run test case ...

Limiting Firebase communication to Electron Application

Is there a way to restrict access to a Firebase realtime database or any other database from an Electron application? I understand that you can restrict access by specifying the server your website is hosted on, but since Electron is local, are there any o ...

Interacting with an XML file contained within a PHP variable using jQuery

I'm pretty new to programming, so please be patient with me =] Currently, I am working on passing a string from the user to an API using PHP. The API then responds with an XML file, which I store under $response. So far, everything is running smoothl ...

Obtain JSON data from an API and display it in a table using axios and Vue.js

I am working with a datatable and trying to populate it with data fetched from an API that returns JSON using the findAll() method from Sequelize. However, when I call the getUser method in console.log, it shows that the data is being retrieved. But when ...

The Firebase function that reloads the auth currentUser is not refreshing properly within a Vue component

My function for updating the profile URL using the reload method is not reflecting changes in my computed property. Computed Property computed: { photoUrl: function() { return firebase.auth().currentUser.photoURL; }, } Function onFileC ...

JavaScript validation failing to validate number ranges for 4-digit numbers

Currently, I am facing an issue with validating numbers entered between two text boxes to ensure that the first number is not greater than the second number. The validation process seems to work fine for three-digit numbers (e.g., 800 - 900), but it fails ...

The component is failing to store its value within the database

I'm encountering an problem when attempting to save an option in the database. To address this issue, I created a component in Svelte called StatePicker that is responsible for saving US States. However, when I try to save it in the database using a ...

Filling a HTML div with data through PageMethods and AJAX

My issue is quite unique. Despite checking numerous examples before reaching out here, I am facing a peculiar problem. I have a div element in my ASPX file and I am using AJAX to send a POST request to populate it. <script> function send(input ...

Ways to ensure that ng-click is triggered exclusively on the click event

I am a beginner in Angular and attempting to toggle a class on click only for the current link. However, when I click, it is affecting all links instead of just the current one. I would like it to work only on the current element, similar to how we use "(t ...

What is the best way to capture a screenshot using selenium in conjunction with synchronous JavaScript?

Currently, I am developing an automated test using javaScript and leveraging a node library called webdriver-sync. This library simplifies writing selenium tests by eliminating the need for callbacks and promises, and it utilizes the java Webdriver API. Su ...

Trying out the ClientPortal in Next.JS with Jest Testing

I'm currently working with NextJS and I want to run tests on the ClientPortal component. My testing toolkit consists of Jest and React Testing Library. Below is a sample code snippet for the ClientPortal component: import { useEffect, useRef, useStat ...

Fulfill the specified amounts for each row within a collection of items

I have an array of objects containing quantities. Each object includes a key indicating the amount to fill (amountToFill) and another key representing the already filled amount (amountFilled). The goal is to specify a quantity (amount: number = 50;) and au ...

Grouping results by month according to the datetime object in C#

I am working on an ASP.NET MVC application that includes a line chart displaying record counts and months on the X-axis and Y-axis respectively. To achieve this, I need to make an ajax call to the controller where the model holds information such as the r ...

Verifying whether an item shows potential for being a successful function

When using protractor.js, I am working with functions that utilize promises/defer. For instance: var myFunc = function(_params) { var deferred = protractor.promise.defer(); /***do some magic code***/ /****wait for other promises****/ /*****deferr ...

Can the concept of partial class be used in an AngularJS controller?

Is it possible to organize code into groups using partials in angularjs? The issue is that my controller has become too cluttered with a lot of code for different methods and functionalities, making it difficult to read. I want to maintain the same contro ...

Is there a tool or software available that can securely encode a text file into an HTML file without the need for loading it using AJAX?

At the moment, I'm using jQuery to load a txt file (in utf-8) via $.ajax. The txt file has some break lines, such as: line1 line2 line3 When loaded through AJAX into a variable, it appears as: line1\n\nline2\nline3 I could manuall ...