In what way can I ensure that the value of currentIndex is consistently set to 0 before each calculation?

Is there a way to set the Value of currentIndex to always be 0?

The calculation of (CRANK1 + CRANK2) + (DRANK1 + DRANK2) should result in (0 + selected amount), but it is currently calculating as (selected amount + selected amount).

Any assistance would be greatly appreciated. Thank you. MOSTLY CODE IN POST, NEED TEXT MOSTLY CODE IN POST, NEED TEXT MOSTLY CODE IN POST, NEED TEXT

var current_division,
    desired_division;

var prices = [
00,09,09,09,09,
12,12,14,14,14,
17,17,17,17,19,
23,24,25,28,28,
35,40,50,65,85,
120,00,00,00,00
];


function getCurrentIndex() {
  return (+document.getElementById("CRANK1").value + 
    +document.getElementById("CRANK2").value);

}

function getDesiredIndex() {
  return (+document.getElementById("DRANK1").value + 
    +document.getElementById("DRANK2").value);
}


function total() {
  var currentIndex = getCurrentIndex();
  var desiredIndex = getDesiredIndex();

   if (desiredIndex < currentIndex) {
    document.getElementById('prices').value = "You can't rank backwards";
    return;
  }

  var accumulatedPrice = 0;
  for(var i = currentIndex; i <= desiredIndex; i++) {
    accumulatedPrice += prices[i];
  }

  document.getElementById('prices').value = accumulatedPrice;
  document.getElementById("prices").readOnly = true;

}

document.getElementById('divboost').addEventListener('change', function() {
  total();
})

HTML

  <form id="divboost" name="priceCalc" action="">
    <br/>
    <select id="CRANK1"> Current Rank
          <option value="0">Bronze</option>
          <option value="5">Silver</option>
          <option value="10">Gold</option>
          <option value="15">Platinum</option>
          <option value="20">Diamond</option>
      </select>
    <br>
    <br/>
    <select id="CRANK2"> Current Divison
          <option value="0">Division 5</option>
          <option value="1">Division 4</option>
          <option value="2">Division 3</option>
          <option value="3">Division 2</option>
          <option value="4">Division 1</option>
      </select>
    <br>
    <br>
    <br/>
    <br/>
    <select id="DRANK1"> Desired Rank
          <option value="0">Bronze</option>
          <option value="5">Silver</option>
          <option value="10">Gold</option>
          <option value="15">Platinum</option>
          <option value="20">Diamond</option>
          <option value="25">Master</option>
      </select>
    <br>
    <br/>
    <select id="DRANK2"> Desired Divison
          <option value="0">Division 5</option>
          <option value="1">Division 4</option>
          <option value="2">Division 3</option>
          <option value="3">Division 2</option>
          <option value="4">Division 1</option>
      </select>
    <br>
    <br>
    € <input type="text" id="prices">
    <br/>
    <br>
  </form>

Answer №1

Exploring further, I realized that the initial currentIndex should not be included in the accumulatedPrice.

To achieve the desired outcome, increment the currentIndex just before the loop.

  var accumulatedPrice = 0;
  currentIndex++;
  for(var i = currentIndex; i <= desiredIndex; i++) {
    accumulatedPrice += prices[i];
  }

Alternatively, you can add 1 to the result of your getCurrentIndex() function.

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

How can I create a dashed border for a pie chart using highcharts?

Is there a way to change the default solid border of a pie highchart to dashed? This modification is only necessary for pies without data or with negative data values. Perhaps it's possible to redraw the SVG of the border, like in this example: https: ...

What is causing the TypeError in Discord.js when trying to read the 'voice' property? Any help troubleshooting this issue would be greatly appreciated

Hey everyone, I'm having an issue with my play.js file that I obtained from a Source Bin. If anyone could provide some assistance, it would be greatly appreciated. const ytdl = require("ytdl-core"); const ytSearch = require("yt-search"); //Global que ...

Generating animated particles using three.js

I'm diving into the world of three.js and have managed to create a basic particle app using it. However, I've noticed that the particles flow from the center, but I'd like them to move in a direction similar to what's shown in the scree ...

What is the process for including a new item in the p-breadcrumb list?

Having trouble getting my code to add a new item to the p-breadcrumb list on click. Any assistance would be greatly appreciated. Thank you in advance! Check out the live demo here ngOnInit() { this.items = [ {label: 'Computer'}, ...

What is the best way for me to determine the average number of likes on a post?

I have a Post model with various fields such as author, content, views, likedBy, tags, and comments. model Post { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt id String @id @default(cuid()) author U ...

The largest contentful paint is anticipating an unidentified event

My website is encountering issues with Google Pagespeed and I'm unsure of the cause. The primary bottleneck appears to be the LCP time, which Google reports as taking between 7 and 11 seconds during each test. Upon analyzing the waterfall chart, it ...

Instructions on incorporating a regular expression test within an array find operation

My array looks like this: const arr = [{id: "12f"},{id: "12F"},{id: "13"}] const itemToBeFound = {id: "12f"} I'm trying to locate that item using a method like RegExp(/12f/i).test(string) The reason for using the regexp is to make the search case ...

How can the AngularJS model be updated while using long polling with Ajax?

How can I update the model using ajax long polling method? To start, I will load the default list: For example: - id1 - id2 - id3 Next, I set up an ajax long polling process in the background that runs every 5 seconds. When the ajax call receives an upd ...

End: unrelated, lacking responses

I have a question I'd like to discuss: Whenever I utilize the following code snippet: async function createNewElement(req,res){ const start1 = new Date().getTime(); console.log("start time 1 ", start1) await new Promise((resolve) => setT ...

Tips for utilizing a variable selector with jQuery's .attr() method

In a jQuery DataTable, there is a scenario where some values can be modified by clicking an edit button. When clicked, a modal popup appears with a form to enter new values for notes and status: ... "columnDefs": [ { ...

Passing a JSON object between pages in Next.js using props during programmatic navigation

In my Next.js project, I have two pages. On the first page, the user fills out a form to create a post. The information is stored in a large JSON object, which needs to be passed to the second page for the user to preview the post before finalizing it. Wi ...

Retrieve data from multiple JSON tables using a JavaScript loop

Check out this Codepen for a working example. I am relatively new to Javascript, so I may not be approaching this problem the best way. If you have any suggestions on how I could improve my approach, I would greatly appreciate it; always looking to learn ...

What are the specific circumstances in which the onerror and ontimeout properties are utilized? (regarding

When utilizing the XMLHttpRequest class to send payload data from a web client to a web server, I encounter some common errors that need to be handled... REQUEST TIMEOUT (CONNECTION TIMEOUT) 500, INTERNAL SERVER ERROR 502, BAD GATEWAY 503, SERVICE UNAVAI ...

What steps should I take to generate a 2-Dimension Input Array from scratch?

I am working on a project that involves creating a 2-Dimensional array of text-based numerical inputs. I aim to use the standard HTML input type box for this purpose: <input type="text"> The number of rows and columns in the array will depend o ...

Step-by-step guide to showing the contents of every file in a directory on the console using node.js or express

Having trouble retrieving file contents from a folder using Node.js I can successfully retrieve the contents of one file using the read function, but unable to retrieve contents of all files at once. ...

Is there a way to change the text (price) when I select an option?

<div class="single-pro-details"> <!--Customize in the CSS--> <h6>Home / Beats</h6> <h4>Unique Lil Tecca Type Beat - New Love</h4> <h2 id="price">$ ...

Calculate the total sum by adding the values of the radio buttons that have been selected and then display or

Seeking help to troubleshoot my code! I want to calculate the sum of selected radio button values and display it at the end. Can anyone assist me with this issue? Thanks in advance! <html> <head> </head> <script type="text/javas ...

Having trouble getting a Chrome extension/jQuery to work on certain sites but not others? Attempting to trigger an event when a link is clicked

For three different websites, I have three separate js files. I want to mention that the manifest has the correct settings to make sure these files work on the right sites, but unfortunately, only one function of the extension (the most important one) is n ...

Implementing Ajax Js to search within a specific div - reducing text overload on the page

Our e-shop on Prestashop requires an Ajax search feature to find compatible batteries and adapters on the page. Here is the code I have created: https://jsfiddle.net/fgfjo2n9/ I am facing two issues: • 1st I want the output to only display the heading ...

Flawless Carousel - Flipping the Sequence

I am currently implementing Slick Carousel on a website that I am working on. One challenge I am encountering is trying to get the "slider-nav" to move in the opposite direction than it normally does. For instance, at the moment, the order goes like this ...