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
  • 204,283
  • 31
  • 260
  • 272
slevin
  • 4,166
  • 20
  • 69
  • 129

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
  • 1,031,962
  • 187
  • 1,923
  • 1,875
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,433
  • 2
  • 40
  • 70
0

Try

this['newtextLink' + (g + 1)] = ...;
beautifulcoder
  • 10,832
  • 3
  • 19
  • 29
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,170
  • 7
  • 25