[thelist] Javascript var + string

Tom Dell'Aringa pixelmech at yahoo.com
Mon Jul 7 13:19:00 CDT 2003


--- Fabio Gomes <flgomes at fazenda.sp.gov.br> wrote:
> In searching of a smaller code in my javascript I'm looking for
> some code to replace the following lines (for instance):
> 
>    if(document.form.textfield_1.value == ""){
>      return false;
>    }
>    if(document.form.textfield_2.value == ""){
>      return false;
>    }
>    if(document.form.textfield_3.value == ""){
>      return false;
>    }
> 
>    With those:
> 
>    for(COUNT=0; COUNT<=3;COUNT++){
>      var TheTextField = 'document.form.textfield_' + COUNT +
> '.value';
>      if(TheTextField == ""){
>        return false;
>      }
>    }

Fabio,

I'm not sure if this is all you have for this function, but I would
do it like so:

function Fabio() {
  var oForm = document.forms['formName'];
  var numFields = arguments.length;
  for(i=0; i<numFields; i++) {
    if(oForm.elements[arguments[i]].value == "") return false;
  }
}

Then when I call the function, I would send my text field NAMES as
arguments (parameters) like:

onclick="function Fabio('field1', 'field2', 'etc');"

 JS automatically makes an array of arguments you send it, which you
can use. I get the length of that array with the length property and
use that in my for loop.

Now I have the right size for loop and your 3 (or however many) text
field names. I then check each value for empty and return out if it
is such.

This way, you don't have to change your function if your number of
fields changes, just change your function call. There are other
slight variations you could do on this (you could send the form as an
object as well to really abstract it).

HTH

Tom

=====
http://www.pixelmech.com/ :: Web Development Services
http://www.DMXzone.com/ :: Premium Content Author / JavaScript / Every Friday!
http://www.maccaws.com/ :: Group Leader
[Making A Commercial Case for Adopting Web Standards]

"That's not art, that's just annoying." -- Squidward


More information about the thelist mailing list