Click to See Complete Forum and Search --> : help with a loop please
rjusa
12-04-2003, 08:02 AM
I have the following
function Fchanger() {
if(document.forms[0].state1.value.length > 0)
document.forms[0].state1.style.borderColor='#000000';
if(document.forms[0].state1.value.length > 0)
document.forms[0].state1.style.borderWidth='1px';
if(document.forms[0].state1.value.length > 0)
document.forms[0].state1.style.borderStyle='solid';
}
I'd rather not write this out for all 50 states (6 lines x 50 states =300 lines !). Is there a way I can "loop" this to cover all the states and keep the code manageable?
Thanks,
Ron
Pittimann
12-04-2003, 08:48 AM
Hi!
Try something like this:
<script type="text/javascript">
<!--
function Fchanger() {
//all states have to go into the array like "Name1","Name2"...
allStates = new Array("Alabama","Hawaii","Michigan","Virginia","Washington");
for (var i = 0; i < allStates.length; i++) {
if (document.myForm[allStates[i]].value.length >0){
document.myForm[allStates[i]].style.borderColor='#000000';
document.myForm[allStates[i]].style.borderWidth='1px';
document.myForm[allStates[i]].style.borderStyle='solid';
}
}
}
//-->
</script>
By the way (1): it is not necessary to repeat the same if condition 3 times in your example. That would do as well:
function Fchanger() {
if(document.forms[0].state1.value.length > 0) {
document.forms[0].state1.style.borderColor='#000000';
document.forms[0].state1.style.borderWidth='1px';
document.forms[0].state1.style.borderStyle='solid';
}
}
By the way (2): in CSS you could also define two classes for the form elements. One is assigned in the hard code and another one with your three style attributes which you assign in your function. Then you would just have to change the class...
Cheers - Pit
batfink
12-04-2003, 09:11 AM
If each element had an id it would be even easier.
function Fchanger()
{
a=document;
for(i=1;i<51;i++)
{
if(a.getElementById("state" + i).value.length > 0)
{
a.getElementById("state" + i).style.borderColor='#000000';
a.getElementById("state" + i).style.borderWidth='1px';
a.getElementById("state" + i).style.borderStyle='solid';
}
}
}
rjusa
12-04-2003, 09:48 AM
Hey Pittimann,
Thanks alot for your help. I constructed the 50 state array and used your code, even renamed the form myForm. When I go to run the script I get
'doc.myForm[...].value' is null or not an object...
What'd I screw up?
Thanks again,
Ron
Pittimann
12-04-2003, 09:57 AM
Hi!
Sorry - I thought, I posted the form as well. I didn't (f..k)!
the names of the formfields have to be the names in the array, but you should really consider batfinks proposal.
Well - to get "my" stuff work, just name the formfields and the stuff will work.
Sorry again for not pasting the form into my post last time.
Cheers - Pit