0

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.

0

4 Answers 4

1

Try replacing the line

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

for

var SitePhone= document.getElementsByName(site[i])[0].value;
Sign up to request clarification or add additional context in comments.

Comments

0

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;  

2 Comments

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. Any ideas.
Oh, so site isn't an array that contains names? See my edit.
0

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.

Comments

0

Try

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.