I have a form and would like to verify that a few fields that it contains have an entry.
As such I have the following:
var requiredFields = array(
'Delivery_first_name',
'Delivery_last_name',
'Delivery_address',
'Delivery_city',
'Delivery_zip',
'Delivery_phone'
);
for(var field in requiredFields)
{
if(document.ezpay.field.value.length == 0)
{
document.ezpay.field.style.cssText = 'background:red;';
}
}
However it does not appear to be working. My thoughts are that the field portion of if(document.ezpay.field.value.length == 0)” is not being evaluated.
In other words, the statement is executing as if(document.ezpay.field.value.length == 0) rather than if(document.ezpay.Delivery_first_name.value.length == 0).
Can anyone confirm that belief and more importantly give me some guidance as to why the above is not working?
The goal of the above is to iterate through the defined fields and set the CSS style background to red for any fields that are empty.
Thanks! 🙂
Firstly, you shouldn’t iterate over an array using
for...inas that construct is for enumerating object properties.Secondly, you are trying to access a property named
fieldwhen what you want is to access a property whose name is contained in a variable namedfield. Try: