Click to See Complete Forum and Search --> : Variable not working


florida
11-24-2003, 05:41 AM
I have this validation that works:

<script>
var RegEx = /^\s*$/;
function Val()
{
if((RegEx.test(document.thePage.subject.value))
&& (RegEx.test(document.thePage.question.value))
&& (RegEx.test(document.thePage.answer.value)))
{
alert("No data entered.");
return false;
}
}
</script>

I was hoping to make it shorter by putting 'document.thePage' in a variable. But the below doesnt work or validate. Please advise.


<script>
var RegEx = /^\s*$/;
var q = document.thePage;
function Val()
{
if((RegEx.test(q.subject.value))
&& (RegEx.test(q.question.value))
&& (RegEx.test(q.answer.value)))
{
alert("No data entered.");
return false;
}
}
</script>

Gollum
11-24-2003, 06:50 AM
Your problem lies with the declaration of q.
When the browser is parsing the HTML document, when it comes across any <script> tags, it will execute it as it runs, including the line:

var q = document.thePage;

Now, presuming you put your <script> in the <head> section of your page, the form called "thePage" hasn't been parsed yet and so your q variable will be set to the value of undefined.

To fix: put that statement inside your Val() function so that it is executed each time the function is run (and after thePage has been parsed).

florida
11-24-2003, 06:56 AM
Thank you.