0

Does anyone know why this javascript isn't working ? Its returning the field is empty when its not

The html i'm using on the form is:

 onsubmit="return validate_form ( );" method="post" name="AddPTR"

And the javascript is:

<script type="text/javascript">
function validate_form ( )
{
valid = true;

if ( document.forms.AddPTR.PTR2.value == "" )
{
    alert ( "Please fill in the PTR box." );
    valid = false;
}

return valid;
}

</script>
3
  • Where's the HTML of the input field? Commented Oct 31, 2011 at 15:58
  • 2
    Probably you are getting a null reference somewhere in the following chain: document.forms.AddPTR.PTR2.value. Also when declaring a local variable in javascript it is a good practice to put a var. So var valid = true;. This avoids polluting the global scope. Commented Oct 31, 2011 at 15:58
  • 1
    Should work fine, see example: jsfiddle.net/ezDR4 Commented Oct 31, 2011 at 16:01

1 Answer 1

5

document.forms is a standard DOM property that holds an array with the <form> tags in the document.

If you want to access the AddPTR form, you can do it in two ways:

  • If you've only got one <form> in the document, or know the order they are in, you can access the array by index: document.forms[0].
  • If you want to get the <form> by its name AddPTR, you can get it from the document.forms property accessing it as an associative array: document.forms["AddPTR"]. This approach has the advantage of being independent from the document layout.

See this W3C link for some information on how to access associative arrays: Objects in JavaScript: Objects as associative arrays

Sign up to request clarification or add additional context in comments.

5 Comments

Hi, I've just tried using if ( document.forms["AddPTR"][PTR2].value == "" ) And still no luck, Any idea ?
Just use document.forms["AddPTR"].PTR2.value == "" or document.forms[0].PTR2.value == "". You could also do document.forms["AddPTR"]["PTR2"].value == "". Remember to use a string for the key when accessing the array as an associative array.
Hello, The 1st and 3rd option you suggested show the please fill in field message even if field is filled in, the 2nd suggestion doesn't show the message if empty or filled
Which browser are you using? Check if it works for you in this fiddle
So, check if you've got the same structure in your page. Is PTR2 the name of an <input> element that is a direct child of the <form>? Debug which access in that sentence is failing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.