Entry
How can I check whether document.formName.fieldName is an array or a single object?
Mar 8th, 2000 09:38
Martin Honnen,
If you have more than one form element with the same name this is
reflected in client side JavaScript as an array
document.formName.fieldName
of input objects. Generic code often doesn't know whether you have a
single radio button or checkbox with a certain name or multiple. So you
need a way in your code to check whether what you handle is a single
input object or an array of input objects.
As arrays of input objects do have a length property greater than 0 the
check is easy
if (document.formName.fieldName.length)
// we have an array
else
// we have a single input
The following is an example application of generic code checking a
radio button or a radio button group:
<HTML>
<HEAD>
<SCRIPT>
function checkRadios (form, fieldName) {
var checked = false;
if (form[fieldName].length) {
for (var i = 0; i < form[fieldName].length; i++)
if ((checked = form[fieldName][i].checked))
break;
}
else
checked = form[fieldName].checked;
if (!checked) {
alert('Please check radio button ' + fieldName);
var b = form[fieldName].length ? form[fieldName][0] : form
[fieldName];
b.focus();
return false;
}
else
return true;
}
</SCRIPT>
<SCRIPT>
function validateRadios () {
return checkRadios(document.formName, 'religion')
&& checkRadios(document.formName, 'god');
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="formName" ONSUBMIT="return validateRadios()">
Religion:
<INPUT TYPE="radio" NAME="religion" VALUE="Kibology">
Kibology
<INPUT TYPE="radio" NAME="religion" VALUE="Xibology">
Xibology
<BR>
God:
<INPUT TYPE="radio" NAME="god" VALUE="Kibo">
Kibo
<BR>
<INPUT TYPE="submit">
</FORM>
</BODY>
</HTML>