Page 1 of 1

Javascript - passing array?

Posted: Sun Oct 09, 2005 3:43 pm
by Ree
I have the following function to allert a user if a required field is found empty:

Code: Select all

function check_empty(fields)
{
  length = fields.length;
  for (i = 0; i < length; i++)
  {
    if (document.forms[0].fields[i].value == '')
    {
      alert(fields[i] + ' cannot be empty.');
      return false;
    }
  } 
}
The form has this attribute:

Code: Select all

onsubmit="return check_empty(['head', 'fck'])"
I pass an array of field names ('head' and 'fck'). It doesn't work. Where is the prob?

Posted: Sun Oct 09, 2005 4:04 pm
by feyd

Code: Select all

document.forms[0].elements[fields[i]].value == ''

Posted: Sun Oct 09, 2005 4:08 pm
by Ree
Works very well, thanks a lot. But why elements array? Why won't it work the way I wrote? You can reference a field using document.formname.fieldname after all...

Posted: Sun Oct 09, 2005 4:40 pm
by feyd
it was looking for 'fields' as a property/child of the form object, which it is not.

Posted: Tue Oct 11, 2005 6:27 am
by Ree
All right, but have a look at this:

Code: Select all

function check_empty(fields)
{
  length = fields.length;
  for (i = 0; i < length; i++)
  {
    if (document.forms[0].elements[fields[i][0]].value == '')
    {
      alert(fields[i][1] + ' field cannot be empty.');
      document.forms[0].elements[fields[i][0]].focus();      
      return false;
    }
  }
}

<form method="post" ... onsubmit="return check_empty([['head', 'Headline'], ['fck', 'Body']])">
  ...
</form>
This works with FF, but not with IE. Any ideas why?

Posted: Tue Oct 11, 2005 1:12 pm
by Ree
Ok, so I've found what the problem with IE was - it didn't like 'length' as variable name. Weird, but what the heck, I changed it and now it works:

Code: Select all

function check_empty(fields)
{
  l = fields.length;
  for (i = 0; i < l; i++)
  {
    if (document.forms[0].elements[fields[i][0]].value == '')
    {
      alert(fields[i][1] + ' field cannot be empty.');
      document.forms[0].elements[fields[i][0]].focus();     
      return false;
    }
  }
}
However I have yet another question about weird behaviour of both IE and FF when using FCKeditor.

IE:

When FCKeditor area is empty, IE pops the alert as required, but it ALSO submits the form right after that which shouldn't happen.

FF:

When FCKeditor area is empty, FF pops the alert as required and doesn't submit the form. BUT if the area is filled, the first time form submission button is pressed, it still pops the alert. When you press the form button again, the form is submitted fine.

Any of you had some similar problems before? I'm really unsure what the problem could be, the JS function I use is really simple. What could be the cause of this weird behaviour?

feyd? :)