tags:

views:

43

answers:

3

in my code i called a javascript function onsubmit of a form and inside the function making validation to my fields by using formname.fieldname.value and it works fine but suddenly it doesn't work display me an error "formname is not defined".

Thanks in advance

+1  A: 

Some possible reasons:

  • you added another object with the same name on that page
  • you changed the name of the form
  • the name attribute is no longer there on the form tag
RedFilter
+1  A: 

if you could post your code, that would help, but I think I know what's going on anyway. Inside the onsubmit function, it doesn't have the right variable scope. I usually get around this by passing a reference to the <form> to the function, which is really easy.

<form onsubmit="return doValidation(this);">

and then your javascript:

function doValidation(form) {

    form.fieldOne.value = ... // etc

};

The other way would be to reference it absolutely

<form name="myForm">


function doValidation() {
    var form = document.myForm;
    form.fieldOne.value = ... // etc
}
nickf
A: 

“formname.fieldname.value” is an IE hack that never should have worked anywhere. Don't use it. Forms are not supposed to be registered as global variables (window. members), and there are lots of compatibility problems with it, that may have led your script to ‘stop’ working in some circumstances.

Given:

<form name="foo" method="get" action="/"> ...
<input name="bar" type="text" value="" />

The correct way to access the input with old-school DOM Level 0 HTML methods is:

document.forms.foo.elements.bar

This works across browsers going back to prehistoric Netscape 2 and has a much smaller chance of provoking a name-clash, by using the ‘document.forms’ array instead of the global ‘window’ (an object that has many and increasing members whose names you might accidentally choose).

However these days it is probably easiest to use ID, and DOM Level 1 Core's getElementById method:

<form method="get" action="/"> ...
<input name="bar" type="text" value="" id="field-bar" />

document.getElementById('field-bar')

which is simpler and has no clashes with members of the window, document or form objects.

bobince