0

I have the following basic function:

<script type="text/javascript">
function Form_Data(theForm)
{

var t=1;
while (t<=5) {

if (theForm.F[t]FirstName.value == "")
    {
    alert("Please enter Fighter 1's First Name.");
    theForm.F[t]FirstName.focus();
    return (false);
    }
t++;
}

return (true);
}
</script>

The script (js validation) fails using this code. If I remove the [t] and replace with a number (1,2,3,4,etc), the validation works on the appropriate fields. What am I doing wrong?

10
  • 1
    Note that the parentheses in return statements are not necessary :) Commented May 26, 2010 at 22:26
  • 4
    What exactly are you trying to do? F[t]FirstName looks to me like invalid syntax. Commented May 26, 2010 at 22:27
  • @Matchu - thank you for iterating my question/point. I have errors so something is not right with the code. As I state at the end, if I replace the variable with a number I get my validation. I have over 20 IF statements and up to 16 different 't' values Commented May 26, 2010 at 22:31
  • 1
    @JM4 - Are you replacing the t with a number or are you replacing [t] with a number? Please post a snippet of the code that works. We don't know what your object model looks like. Commented May 26, 2010 at 22:32
  • @tehMick - [t] with a number so the end result would look like: theForm.F3FirstName.value Commented May 26, 2010 at 22:33

1 Answer 1

3

You can't use an index as part of a name, you have to put the name together as a string and use as index:

theForm['F' + t + 'FirstName']
Sign up to request clarification or add additional context in comments.

10 Comments

You don't need both the dot and the brackets.
@JM4 - I removed the syntax error. Looking at the comments, this is the solution to your problem :) Brackets represent accessing a property, not interpolating into a property name.
@Matchu - no this is not, this solution does not work. I have tried it.
@JM4 - Yeah. It is. Given the problem you describe, this is the solution. Please include a more complete code sample in the original question, because there must be an additional issue.
@JM4 - Glad to help :P Just to give that answer a bit of explanation... If I have an object with the property foo, I can get to it with the easier syntax of obj.foo, or I can use obj[foo]. They are completely interchangable. You'll use the first more often, but the second allows you to include some more Javascript code inside the brackets, whereas the first will only take a straight-up, hard-coded property name. Hope that makes things a tad clearer :)
|

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.