[thelist] js function with variable parameters...need advice

.jeff jeff at members.evolt.org
Mon Feb 10 16:32:01 CST 2003


tom,

><><><><><><><><><><><><><><><><><><><><><><><><><><><><><
> From: Tom Dell'Aringa
>
> Hey Volters,
>
> I have a situation where a user changes a dropdown from
> "no" to "yes". When "yes" is selected a *variable*
> number of fields are changed from disabled to enabled to
> allow them to further fill in data.
>
> My simple function to handle it that does work is this:
>
> function enableFields(fieldName)
> {
>    field = document.forms["myForm"].elements[fieldName];
>    field.disabled = false;
> }
>
> and is called on the onChange by doing:
> onChange="enableFields('fieldName')"
>
> I have probably *twenty* of these to handle on one page.
> You can see the function works fine, but how can I make
> it so I can pass any number of field names (actually
> like 1-3 depending on)?
>
> Can I just put say 4 variables in the paramters and
> test to see if they exist? This doesn't seem very
> elegant.
>
> I'm guessing some sort of an array and for loop but I
> can't figure it out..
><><><><><><><><><><><><><><><><><><><><><><><><><><><><><

you're so very close to the solution.  a function has an arguments array.
this array represents all the arguments that were passed in the function
call, regardless of whether or not there are variables for some or all of
the arguments in the function declaration.  i'd suggest you drop the
'fieldName' argument and simply loop over the arguments array.

function enableFields()
{
  for(i = 0; i < arguments.length; i++)
  {
    field = document.forms['myForm'].elements[arguments[i]];
    if(field)
      field.disabled = false;
  }
}

then, calling the function is as simple as:

enabledFields('foo', 'bar', 'boo', 'far');

the call above would attempt to enable form fields named foo, bar, boo, and
far in the form, myForm.

you could even generalize your function a bit further by passing in an
object reference to the form as the first argument.  then you could lose the
'document.forms["myForm"]' reference and replace it with oForm. don't forget
to set your arguments loop to start at 1 instead of 0.

function enableFields(oForm)
{
  for(i = 1; i < arguments.length; i++)
  {
    field = oForm.elements[arguments[i]];
    if(field)
      field.disabled = false;
  }
}

your function call would be slightly altered (assuming it's being called by
an event handler on a form field in the same form as the elements you wish
to enabled:

enabledFields(this.form, 'foo', 'bar', 'boo', 'far');

enjoy,

.jeff

http://evolt.org/
jeff at members.evolt.org
http://members.evolt.org/jeff/




More information about the thelist mailing list