Utilize the for loop with a specific variable

I am in the process of streamlining my code due to repetitive sections. I anticipate needing to utilize this particular example numerous times. My goal is to implement a for loop, but I'm encountering difficulty with increasing my variable. Currently, while my variable is incrementing, I'm struggling to incorporate my cell data into it. It seems like there may be an issue with double assigning the variable h. I'm seeking advice on how to resolve this challenge. Thank you in advance for your assistance.

For Loop


for (var j = 2; j<15; j++) {
  eval("var polebrea" +j);
  var h = ("polebrea" +j);
}

h = document.getElementById("part1Table").rows[10].cells[2].innerHTML;

Attempting To Implement Code


polebrea2 = document.getElementById("part1Table").rows[10].cells[2].innerHTML;
polebrea3 = document.getElementById("part1Table").rows[10].cells[3].innerHTML;
polebrea4 = document.getElementById("part1Table").rows[10].cells[4].innerHTML;
polebrea5 = document.getElementById("part1Table").rows[10].cells[5].innerHTML;

(continued until reaching 15)

Inserting Variable


<script>document.write(polebrea2)</script>

Answer №1

Breaking away from conventional design practices....opt for the string index method when accessing properties to assign values to your variables:

// Storing data in the global window object is not recommended....consider using a separate custom object like var polbreas = {}; 
for (var i = 2; i<15; i++){
    window["polbrea"+i] = document.getElementById("part1Table").rows[10].cells[i].innerHTML;
}

Answer №2

Although it is not considered best practice, you could experiment with the following approach:

function generateDynamicVariable( index ){
    var variableName = "polebrea" + index;
    var objName = document.getElementById("part1Table").rows[10].cells[index].innerHTML;
    return (variableName + " = " + objName + ";");
};

for (var k = 2; k<15; k++){
        var dynamicVar = generateDynamicVariable(k);
        console.log( dynamicVar );
} 

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 best way to make a Modal triggered by a loop embedded within a table function properly on mobile devices?

While the modal is functioning properly on desktop, it seems to be encountering issues on mobile devices. The modal appears behind the background and is confined by the boundaries of the table (tbody). Below is the code snippet for triggering the modal: ...

The Gulpfile.js encountered an error while trying to load

My Visual Studio task runner is having trouble loading the gulp file. I am currently using VS2017 v15.9.4, but the project was developed some years ago. Failed to run "...\Gulpfile.js"... cmd.exe /c gulp --tasks-simple assert.js:350 throw err; ...

Issue with showing helper text in MUI date picker when utilizing react-hook-form library

I have been using the react-hook-form library in combination with material-ui. One issue I am encountering is displaying a mandatory field error message for the date picker using the helper text attribute of MUI. Despite getting error messages for the text ...

Can a web application be developed utilizing JavaScript to access the torch feature in Safari?

Currently working on a website that needs to utilize the flashlight feature on both android and IOS devices. Found a method to activate the torch from an android device using Chrome (link). However, this same code does not seem to be functional on my IOS d ...

Distance Calculator for Geolocation WatchPosition

I am currently utilizing geolocation to track the user's current location and keep an eye on it using the watchPosition method. Is there a way to determine the distance between the starting position of the user and their current position? Here is the ...

Is there a way to cancel a fetch request and initiate a new one right away?

Below is an illustration taken from MDN. The example showcases two buttons - one for sending a request and the other for canceling it. var controller = new AbortController(); var signal = controller.signal; var downloadBtn = document.querySelector(&apos ...

Executing Javascript requests on a php server hosted on the web

I'm facing a major issue in my application. I have an app that interacts with a PHP webservice and retrieves data upon button press. However, the service is unresponsive, and I'm struggling to identify the root cause. My intention is to send &ap ...

Find out the keycode of an event in ReactJS when a key is released

Whenever I try to get keyCode on a keyUp event, it always returns 0. Why is this happening? I want to avoid using keypress and similar methods, and I also need to utilize an arrow function: handleKeyPress = (e, type) => { let KeyCode = e.charCode; ...

Display HTML in JavaScript without altering the Document Object Model

Is it possible to style a custom HTML tag called "location" without directly modifying the DOM? For instance, having <location loc-id="14" address="blah" zipcode="14" /> Would it be feasible to render it like this: <div class="location"> ...

Ways to retrieve information beyond the scope of the 'then' method

One issue I am facing involves a piece of code that is only accessible inside of the 'then' function. I need to access it outside of this block in order to utilize it in other parts of my program. $scope.model = {'first_name':'&ap ...

Focused Filtering in DataGrid Pagination

Seeking to adjust the font size of numerical values (10, 25, and 50 as shown in the screenshot below) within rows per page selection within a pagination section of a DataGrid component. https://i.sstatic.net/PnIDa.png After inspecting each number, it was ...

Is there a way to eliminate curly braces from JSON strings with a regular expression?

Hello, I am working with a JSON file and I need to manipulate the content of the chapters array. Specifically, I want to remove the curly braces from inside the strings but only if they contain more than three words (two spaces). Is it achievable using Reg ...

Navigating through different sections of your Angular app can be easily accomplished using

My current project structure is set up like this: The application I am working on is hosted in a subdirectory called /my-scripts/vk.plants. This means that when I request this URL, it loads layout.html and returns it to the user. layout.html contains the ...

What changes can I make to my method in order to utilize async/await?

Within my React application, I have implemented a post request to the server using axios: onSubmit = async (results) => { try { const response = await axios.post("http://localhost:8080/simulate/", results); this.setState({results: ...

Unable to trigger the window's onpopstate event when testing React components

I am facing a challenge with testing a code that is triggered upon navigating through the browser's back/forward arrow click event. The code utilizes an event listener, and I need to verify its functionality using the react testing library. const useW ...

Combining Javascript and Django for a powerful web development solution

Having trouble setting up JS on my Django web app, despite reading through the documentation and previous queries. Using the Django dev server with the following file structure: mysite/ __init__.py MySiteDB manage.py settings.py ...

Can the top header stay fixed to the top of the screen even when scrolling down?

Code snippet: http://jsfiddle.net/R3G2K/1/ In my project, there are multiple divs with content and each div has a header. My goal is to make the last header that goes out of viewport "sticky" or fixed at the top. I have explored various solutions for thi ...

How to retrieve a nested array element in JavaScript

Here is the Pastebin link of the index.html file for reference: http://pastebin.com/g8WpX6Wn (The file contains broken image links and no CSS styling). If you would like to access the entire project, you can download the zip file. I am currently working ...

Issue with displaying entire object using Jest and console.dir

I'm having trouble displaying an error in my Jest test because it's not showing all the levels as expected. import util from 'util' describe('Module', () => { it('should display all levels WITHOUT util', () =& ...

Top method for generating intricate HTML elements sent by the server in real-time

When a Mouse click event occurs, I want to populate a <div> with a form. I have set up the jQuery to send a request to the server and receive the form as plain text. My question is: if I use the innerHTML method to add the form to the <div>, w ...