Bifterss
Bifterss

Reputation: 293

Dynamically create variable in JavaScript function

I cannot get this to work:

function formvalidation()
{
  var SiteNum= document.getElementsByName("sitesinput")[0].value;           
  var i=1;
  while (i<=SiteNum)
  {
    var SitePhone= document.getElementsByName(site['i'])[0].value;  
    alert(SitePhone);
    i++;
  }
}

If I alert like so: alert('document.getElementsByName(site["'+i+'"])[0].value'); it will display the following:

document.getElementsByName(site["1"])[0].value
document.getElementsByName(site["2"])[0].value
document.getElementsByName(site["3"])[0].value

But I cannot get it to go into a variable.

Thanks for looking, B.

Upvotes: 0

Views: 509

Answers (4)

Matt Ball
Matt Ball

Reputation: 359826

Remove the quotes from i. Use a for loop since it fits the use case better than a while loop.

function formvalidation()
{
    var SiteNum= document.getElementsByName("sitesinput")[0].value,
        SitePhone;

    for(var i=1; i<=SiteNum; i++)
    {
        SitePhone = document.getElementsByName(site[i])[0].value;  
        alert(SitePhone);
    }
}

Also, JavaScript does not have block-level scoping, only function-level.

I like this solution, however it wont work without the quotes (") i.e. if do everything the same, but put the name in myself, like ("site[1]") - it will work.

I see where you're headed now.

SitePhone = document.getElementsByName('site[' + i + ']')[0].value;  

Upvotes: 0

BonyT
BonyT

Reputation: 10940

Try

 alert(document.getElementsByName(site[i])[0].value);

Upvotes: 0

shelman
shelman

Reputation: 2699

You are putting quotes around the i in the line

var SiteNum = document.getElementsByName(site['i'])[0].value

which is looking for the element keyed by the string 'i' instead of the value of the variable i. Try removing the quotes.

Upvotes: 0

Paulo Santos
Paulo Santos

Reputation: 11567

Try replacing the line

var SitePhone= document.getElementsByName(site['i'])[0].value;

for

var SitePhone= document.getElementsByName(site[i])[0].value;

Upvotes: 1

Related Questions