0

In JavaScript I have a for snippet to create new input elements

for(var g = 0; g < psi.length; g++) {
var newtextLink+(g+1)= document.createElement('input');
//continue with setting attributes
}

I want to put together the word newtextLink and the var g to have something like newtextLink2 everytime for is executed...How can I achieve that?

j08691
  • 197,815
  • 30
  • 248
  • 265
slevin
  • 4,150
  • 17
  • 66
  • 121

4 Answers4

5

This is where you usually want an array instead:

var newtextLinks = [];
for(var g = 0; g < psi.length; g++)
{
    newtextLinks[g] = document.createElement('input');
}

Then use them via index variables like that (newtextLink[g], newtextLink[0], etc.).

Alternately, there can be places (probably not here) where you really do want names. You can do that with an object:

var newtextLinks = {};
for(var g = 0; g < psi.length; g++)
{
    newtextLinks["name" + (g+1)] = document.createElement('input');
}

Now you have newtextLinks.name1, newtextLinks.name2, and so on.

But for this purpose, an array seems best.

T.J. Crowder
  • 959,406
  • 173
  • 1,780
  • 1,769
0

If you insist on using the variables, you can do it using the window object:

window['newtextLink' + (g+1)] = document.createElement('input');

Otherwise use an array:

var newTextLinks = [];

...

newTextLinks[g] = document.createElement('input');
Overv
  • 8,173
  • 2
  • 38
  • 69
0

Try

this['newtextLink' + (g + 1)] = ...;
beautifulcoder
  • 9,954
  • 3
  • 18
  • 27
0
function createVariables(){
  var newtextLink= [];

  for (var i = 0; i <= psi.length; ++i) {
      newtextLink[i] = document.createElement('input');
  }

  return newtextLink;
}

you have newtextLink[0] ... newtextLink[n]

you have similar question here: JavaScript: Dynamically Creating Variables for Loops

Community
  • 1
  • 1
X-Pippes
  • 1,142
  • 7
  • 24