What is the method for incorporating a counter variable into a variable's name?

Here's my code, which I know is very inefficient:


var slider1 = new Slider("#survey1", {
    precision: 2,
    value: 5
})
var slider2 = new Slider("#survey2", {
    precision: 2,
    value: 5
})
var slider3 = new Slider("#survey3", {
    precision: 2,
    value: 5
})
var slider4 = new Slider("#survey4", {
    precision: 2,
    value: 5
})
var slider5 = new Slider("#survey5", {
    precision: 2,
    value: 5
})

I know this can be done more efficiently. It should continue up to "#survey13" but for the sake of saving space, I skipped those details. Perhaps using a for loop would make it cleaner? How could I incorporate a counter into the variable name and referenced ID?

Answer №1

Here is how you can achieve the desired result:

let allSliders = [];
for (let index = 1; index <= 13; index++) {
    let slider = new Slider("#survey" + index, {
        precision: 2,
        value: 5
    });
    allSliders.push(slider);
}

Now, slider1 corresponds to allSliders[0], slider2 corresponds to allSliders[1], and so forth.

Answer №2

To create a slider for each item, you can utilize a for loop. Simply add the slider instance to an array for later use.

var options = {
    precision: 2,
    value: 5
};
var slider = [];

for (var i = 1; i <= 13; i++) {
    slider.push(new Slider("#survey" + i, options));
}

If the plugin supports multiple selectors

var slider = new Slider("#survey1, #survey2, #survey3 ...", {
    precision: 2,
    value: 5
});

Alternatively, you can assign a common class to all elements and use that class to assign sliders. This approach is dependent on how Slider is defined.

var slider = new Slider(".slider", {
    precision: 2,
    value: 5
});

Answer №3

Experiment using arrays:

let sliders = [];
let settings = {
   precision: 2,
   value: 5
};
for (let index = 1; index <= 13; index++)
   sliders[index] = new Slider("#survey" + index, settings);

If you prefer named variables, consider using objects:

let sliders = {};
let settings = {
   precision: 2,
   value: 5
};
for (let index = 1; index <= 13; index++)
   sliders['survey' + index] = new Slider("#survey" + index, settings);

Answer №4

Instead of utilizing an array like others have suggested, a more effective approach would be to employ an object:

var identifier = 'poll',
    sliders = {},
    count = 9;

do {
  sliders[identifier + count] = new Slider('#' + identifier + count, {
    precision: 2,
    value: 5
  });
} while(count--);

Subsequently, you can access the object you've generated: sliders.poll1, sliders.poll2, and so on!

Answer №5

It's not possible to alter the referenced id, however, you have the option of generating it with PHP prior to loading the page.

<?php
$i = 0;
for ($i; $i < n; $i++) {
    echo 'var slider = new Slider("#survey' + $i + '", {
        precision: 2,
        value: 5
    })';
}
?>

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

Node.js app not rendering ejs file despite using res.render() method, no error being thrown

I am encountering an issue where, when sending an ejs templated file as a response to a HTTP request, the HTML and CSS render properly but the Javascript does not respond. Even though the Javascript sources are linked in the head of the ejs response, the f ...

How can jQuery be used to split a string and isolate the desired string in the center? For example, if we have a string like: sample_str[targeted_str][other_str

http://jsfiddle.net/150aby4u/ There are several dropdown menus, each with a unique field name that is incremented. The objective is to extract the number in the middle of the string/text after making changes to the dropdown. In this case, we want to retr ...

How to incorporate a hyperlink into an Ajax-generated HTML table

I've successfully used thymeleaf in the past, but I'm having trouble implementing it with JavaScript and Ajax get requests. Essentially, I have a table that is generated dynamically. In my HTML script, an Ajax get request fetches and displays a ...

What is the method for resolving circular references using double closures?

Recently, I came across an article discussing how circular references can lead to memory leaks in internet explorer (IE). The article presented an example involving closures nested within each other to demonstrate how a circular reference could occur: fun ...

Using a parameter as optional in an Arrow Function

My handler function looks like this: handleSelect = (k0, k1, v) => { ... } }; I am looking for a way to make the k1 parameter optional in this function. Is there a recommended approach to achieve this? ...

Here's a step-by-step guide on how to parse JSON information in JavaScript when it's formatted as key-value

I need to parse the JSON data in JavaScript. The data consists of key-value pairs. Data looks like this: {09/02/2014 15:36:25=[33.82, 33.42, 40.83], 08/11/2014 16:25:15=[36.6, 33.42, 40.45], 07/30/2014 08:43:57=[0.0, 0.0, 0.0], 08/12/2014 22:00:52=[77.99 ...

Leveraging the withWidth higher order component (HOC) provided by

I am currently using version 3.9.2 of Material UI and experimenting with the withWidth HOC in a server-side rendered application. When I disable Javascript in the debugger options of Chrome Developer Tools, everything functions as expected by displaying t ...

Retrieving JSON data with jQuery's Ajax functionality

I'm currently developing a web application to handle the administrative tasks for a restaurant. The main functionalities include creating new orders, adding order items, and managing financial overviews. One of the key features is the ability to view ...

How to extract information from a JavaScript object array in Node.js?

Currently, I am attempting to extract data from a JavaScript Object array by providing field names and then storing the data in an array. However, my current approach seems to be yielding incorrect results. Whenever I try to log the values stored in ' ...

Transform an HTML table string into JSON format

I discovered a useful library called table to JSON that allows me to convert an HTML Table to JSON using its ID (#testtable in the example below): var table = $('#testtable').tableToJSON(); alert(JSON.stringify(table)); However, I am interested ...

Converting JavaScript CanvasRenderingContext2D states array into a serialized format

Looking for a way to serialize a canvas' state in order to save it to a database for later restoration. Want to store the data as an object rather than a bitmap file. I've tried using .save() and .restore() on the context object, but they only m ...

Adjust the height for just one md-tab

Looking to find a way to set the height of the content within an <md-tab> element to be 100% in a flexible manner. For example, consider the following structure: <body> <md-content> <md-tabs> <md-tab label= ...

Is OnPush Change Detection failing to detect state changes?

Curious about the issue with the OnPush change detection strategy not functioning properly in this demonstration. My understanding is that OnPush change detection should activate when a property reference changes. To ensure this, a new array must be set e ...

Discovering the screen dimensions or viewport using Javascript in Bootstrap 4

Is there a method to identify the view port/screen size being utilized by Bootstrap 4 using Javascript? I've been struggling to find a dependable way to determine the current view port after a user resizes the browser. I attempted to use the Bootstra ...

Utilizing Vue.js to convert blobs into objects or strings and assign them to application variables

I am currently working on a Vue app and have the following setup: data: function() { return { modules: [], ... Along with the following method: methods: { submitted: function(){ ... axios({method: 'get', ...

Extract objects from a nested array using a specific identifier

In order to obtain data from a nested array of objects using a specific ID, I am facing challenges. My goal is to retrieve this data so that I can utilize it in Angular Gridster 2. Although I have attempted using array.filter, I have struggled to achieve t ...

What is the process for making a nested ordered list in HTML?

How can I efficiently create a nested list structure like the one shown below, using nested JSON objects: Parent 1     a. Sub 1     b. Sub 2          i.Sub Sub 1 ...

Using React Native to integrate a JSON string into a button

I'm currently working on an app to explore the functionality of websockets in react native. I have successfully retrieved data from the websocket in JSON format and can output it to the console using console.log. However, my goal is to display a speci ...

Emphasizing hyperlinks according to the user's scrolling location

Currently, I am attempting to create a feature where links are highlighted when the user scrolls over the corresponding section on the page. However, there seems to be an issue with the functionality as Link 2 is highlighting instead of Link 1 as intende ...

Utilize Vue.js and express.js to distribute HTML files securely

Currently, my tech stack includes Vue.js for the frontend and Express.js for the backend. When I kick off the express.js server using npm start, my goal is to serve the Vue frontend component. By utilizing the Vue generator and Express generator, I attemp ...