views:

50

answers:

1

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?

+3  A: 

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']
Guffa
You don't need both the dot and the brackets.
Eric Mickelsen
@Guffa - thanks but this does not work
JM4
@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
@Matchu - no this is not, this solution does not work. I have tried it.
JM4
@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.
Matchu
@JM4 - you included `.value` still, right?
Matchu
@JM4 - Comment spam, sorry. Here is the a link to what I assume to be the general structure of your document. This fix works: http://jsbin.com/ubazi3/edit (though I note that each error alerts "Fighter 1" instead of "Fighter {t}")
Matchu
@Matchu: Thanks for fixing the error.
Guffa
@Matchu - just value is added - I asumed you mean remove both dots so it was theForm['F' + t + 'FirstName']value - all resolved! Thanks for your help!
JM4
Any way in the alert to also reflect the t value instead of the number 1?
JM4
@JM4 - `alert("Please enter Fighter " + t + "'s First Name.");`
Matchu
@Matchu - no wonder your mom named you awesome
JM4
@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 :)
Matchu
@Matchu: Just a small correction: it's `obj['foo']`, not `obj[foo]`. :)
Guffa
@Guffa - ...heh. It comes full circle, don't it? xD
Matchu