PDA

View Full Version : Form validation: JS reference to <label> returns "Undefined"



fastbill
11-02-2008, 01:34 AM
I have a form with one required field. If the user clicks "Submit" with the field empty, I want to turn the field's label red and redisplay the page without submitting it to the server. The <label> element includes this attribute:

id="LABL"

Firefox 3.0.3 and IE7 both say that "document.rentalRequestForm.LABL" is undefined. (I think this worked in FFox 2.x, but I'm not sure.)

My <form> element is defined this way:

<form name="rentalRequestForm" onSubmit="return check()" ...>

The form field and its label are defined in my HTML this way (in two different columns of a table, so I cannot embed the <input> element within the <label> element):

<label for="id_primaryPhone" id="LABL">Phone number:</label>
<input size="35" type="text" name="primaryPhone" id="id_primaryPhone" class="type16requiredfield" />

The check() function contains this code to test for the field being empty; if so, it is supposed to set the label to red:

if (document.rentalRequestForm.primaryPhone.value=="") {
document.rentalRequestForm.LABL.style.color="red";
document.rentalRequestForm.primaryPhone.focus();
}

When I click the "Submit" button with the primaryPhone field empty, the check() function is executed up to, but not including, the first statement within the "if" block. The browser then submits announces that document.rentalRequestForm.LABL.style is null or not an object (IE) or undefined (FFox: Empty string passed to getElementById()). it then proceeds to post the form to the server with the field's value being "".

Using Firebug, I determined that document.rentalRequestForm.primaryPhone is defined and accessible through JavaScript, but an attempt to display document.rentalRequestForm.LABL returns "Undefined".

I would greatly appreciate all suggestions on how to solve this problem.

Thanks,
FastBill

magicyte
11-02-2008, 02:03 AM
Firefox 3.0.3 and IE7 both say that "document.rentalRequestForm.LABL" is undefined. (I think this worked in FFox 2.x, but I'm not sure.)

Eh, try this:


if (document.rentalRequestForm.primaryPhone.value=="") {
document.getElementById('LABL').style.color="red";
document.rentalRequestForm.primaryPhone.focus();
}

-magicyte

fastbill
11-02-2008, 02:27 AM
MANY Thanks, magicyte! Changing to document.getElementById('LABL') did indeed solve the problem in both IE7 and FF3.0.3.

--FastBill

magicyte
11-02-2008, 02:36 AM
Aye. You are welcome. However, to prevent this from happening in the future, I will explain what the problem was. If you wanted to do it the way you did (w/ document.formname.LABL stuff), simply change id="LABL" to name="LABL". I would highly recommend using document.getElementById() all of the time and giving ids to everything instead of name). Any questions are welcome.

-magicyte