What steps do I need to take in order to make this array equation function properly?

I've developed a Javascript code that calculates the total linear footage based on values entered by the user. Below is the snippet of the JavaScript code...


        var totalLinealFootage = 0;
        for (var i = 0; i <= 24; ++i) 
        {
            var p = +document.getElementById('pf' + i).value;
            var f = +document.getElementById('ff' + i).value;
            var i = (+document.getElementById('if' + i).value)/12;

            if (!isNaN(p) && !isNaN(f) && !isNaN(i)) 
            {
                totalLinealFootage += (f+i)*p;
            }
        }
    

Currently, regardless of the input values I provide, the totalLinealFootage variable remains undefined. What could be causing this issue?

Answer №1

It seems that your use of the variable i is causing issues with your loop. As the loop progresses, changes made to i within the loop may lead to unexpected behavior.

If the line

var i = (+document.getElementById('if' + i).value)/12;
assigns a value greater than 24 to i, the loop will stop prematurely in the next iteration due to the i <= 24 condition.

To avoid this problem, consider using different variable names for your loop index and any values used in calculations.

Answer №2

Instructions:

<input id="pf0" value="1" />
<input id="ff0" value="2" />
<input id="if0" value="3" />

Script:

var totalLinealFootage = 0, index, pf, ff, incrementValue;
for (index = 0; index < 1; index += 1) {
    pf = document.getElementById('pf' + index).value;
    ff = document.getElementById('ff' + index).value;
    incrementValue = (document.getElementById('if' + index).value)/12;
    totalLinealFootage += ((ff+incrementValue)*pf);
    console.log(totalLinealFootage);
}

This solution was successful for me. In agreement with @T.J Crowder's advice, ensure that all required inputs are included from 0 to 24. I made adjustments to the variable naming and placement within the loop to improve clarity and efficiency.

Note: Refer to the initial response for additional insights. It seems the issue stemmed from redefining the variable 'index' inside the loop.

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

To ensure the next line only runs after the line above has finished executing, remember that the function is invoked in HTML

my.component.html <button (click)="refresh()">Refresh</button> my.component.ts refresh() { let self = this; self.isRefresh = true; //1st time self.getfun().then(() => { self.isRefresh = false; ...

Is it possible to retrieve the values of #select1 and #select2 before initiating the AJAX request?

I am presented with the following snippet of HTML code: <select id="choice1"> <option value="0">Option 0</option> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3 ...

Unable to utilize a function within a mongoose schema

I encountered an issue while attempting to access the schema methods of a mongoose schema in TypeScript. Schema const userSchema: Schema<IUser> = new Schema( { name: { type: String, required: [true, "Name is required"], ...

Utilizing jQuery and DOM to interact with form elements

Below is the form content <form method="post"> <input type="hidden" name="resulttype" value="Create"> <table> <tr> <td>Full Name</td> <td><input ...

What causes all the accordion panels to toggle simultaneously in a ReactJs application?

When I click on the + button in my accordion, all the sections open at once. What could be causing this issue? Here is my code: const questions = [ { id:1, question: 'What is React?', answer: 'React is a JavaS ...

Is there a way to dynamically adjust the form action based on whether or not JavaScript is enabled?

Is there a way to make a form default to calling a JavaScript ajax function for output, but switch to a PHP page if the user doesn't have JavaScript enabled? <form class="form-inline" role="form" action="javascript:search();"> <div class=" ...

Converting a string into a list extracted from a text document

Within a file, the data (list) is structured as follows: [5,[5,[5,100,-200],200,-400],300,-500] Upon reading this file in an angular application, the contents are converted into a string object like so: "[5,[5,[5,100,-200],200,-400],300,-500]" Is there ...

Tips for styling the json response received from a servlet with jquery ajax

I am attempting to display a list of users returned from a servlet using jQuery ajax. The first script block is functioning well, successfully presenting the list of users in a formatted manner but experiencing issues passing form parameters such as text a ...

Animating Chart.js 2 from right to left instead of from top to bottom

Here is the issue demonstrated in the jsfiddle below. Initially, the data inserts work well. However, when the data set reaches a cap of 10, an unwanted behavior occurs where the data points are animated top-down instead of moving leftward. This can be qu ...

Grab the div, position it accurately, and initiate an ajax call

So many tasks on my plate, but let's prioritize. Within a <div class="showcase">, I have numerous <div class="game"> elements, each with an onclick="addpop('delpopup.php?id=something&pos=somethingelse&box=image')" Does ...

Node.js and MySQL: Troubles with closing connections - Dealing with asynchronous complexities

I am currently working on a Node program to populate my MySQL database with data from files stored on disk. While the method I'm using seems to be effective, I am facing challenges in ensuring that asynchronous functions complete before ending the con ...

Change the color of the text based on which classes the visitor is currently viewing on the page

I have a sidebar menu in plain html for page navigation, like this: <div class="sidebar"><h2>About us</h2> <h3><a href="#chapter1" class="link">Chapter 1</a></h3> <h3><a href="#chapter2" class="link"> ...

Mastering Cookies in Javascript

I have been exploring the world of cookies in Javascript and decided to create an experimental log-in page. The page is fully functional, but I am interested in displaying the user's username and password using cookies. Is this possible with Javascrip ...

Incorporate JSON Records into a DynamoDB Table Using nodeJS

I am trying to transfer data from my JSON file to DynamoDB using the following code: var AWS = require("aws-sdk"); var fs = require('fs'); AWS.config.update({ region: "us-west-2", endpoint: "http://localhost:8000" }); var docClient = ...

Performing two ajax calls within a non-existent div that has only just been appended

I've been developing a website similar to 9gag. I attempted to incorporate a voting feature created by someone else, as I'm not well-versed in AJAX requests, but it just doesn't seem to be functioning. My index.php file fetches five posts f ...

JS prevents selecting a color again after an image has been selected

Currently on my website, the background color changes when a user enters their desired color. However, I am working on allowing users to input a specific keyword that will change the background to an image associated with that word. For example, if a user ...

when within a 'for in' loop

Querying Object Equivalence: I find myself struggling to comprehend the flow of my code and how I can rectify it. Within the areEqual function, I am comparing the "value" property of two objects. If they match -> isEqual=true -> continue with the ...

Dynamic text display using Bootstrap 3

My current struggle involves the implementation of Bootstrap's collapse class in my project. I am attempting to connect buttons with text located in a separate div in order to properly collapse and display it. While I can easily achieve this in a str ...

Which is better for integrating Google Maps API - JavaScript or PHP?

Is it better to use JavaScript or PHP with the Google Maps API? What are the advantages and disadvantages of each? If I have geocodes stored in a database, should I retrieve them using Ajax and process them with JavaScript, or is PHP a better option? The ...

What is the method for dividing a string using capital letters as a delimiter?

I am currently faced with the challenge of splitting a string based on capital letters. Here is the code I have come up with: let s = 'OzievRQ7O37SB5qG3eLB'; var res = s.split(/(?=[A-Z])/) console.log(res); However, there is an additional re ...