Page 1 of 1

is undefined error

Posted: Tue Mar 13, 2012 3:28 am
by social_experiment
I have a javascript function that checks whether a field is empty or not; the html code

Code: Select all

<label id="name">Name (*)</label>
<input id="fieldName" maxlength="30" name="name" size="30" onblur="return emptyFieldCheck('name');" type="name" />
The javascript in question

Code: Select all

function emptyFieldCheck(field)
{
 var myForm = document.forms[1];
 var fieldName = myForm.field;
 var textField = fieldName.value;

 if (textField == '') {
    alert('Error message');
    return false;
  }

  return true;
}
The error message is receive from the error console is fieldName is undefined; Any ideas? The code works if i replace 'field' with 'name' but i would like the function to be reuseable.

Thanks in advance

Re: is undefined error

Posted: Tue Mar 13, 2012 4:22 am
by theserve
in your function it looks like you are trying to check the value of the form directly rather than using the value passed through.

Try changing this line:

var fieldName = myForm.field;

to

var fieldName = field;

Re: is undefined error

Posted: Tue Mar 13, 2012 4:47 am
by social_experiment
Thanks for the feedback; It didn't work but i went a different route when you mentioned that i was trying to access the form as opposed to the value;

Code: Select all

var fieldName = document.getElementById(field);
var textField = fieldName.value;
The removes the need for var myForm = document.forms[1]; aswell;

What i don't understand is that using the value from the input field "name" attribute outright like this works

Code: Select all

var emailField = myForm.email.value; 
but in my function it doesn't work; does javascript assume i am looking for a field with name attribute value of 'field' in this situation?

Re: is undefined error

Posted: Tue Mar 13, 2012 6:13 am
by requinix
social_experiment wrote:does javascript assume i am looking for a field with name attribute value of 'field' in this situation?
Yes.

theserve has the right idea but it needs a little more:

Code: Select all

return emptyFieldCheck(this);

Code: Select all

function emptyFieldCheck(field)
{
 var textField = field.value;