Javascript form specification
I have multiple forms on a web page that were created using JavaScript and I would like to populate a field in the appropriate form with a value (startDate).
I have tried the following code:
oForm = document.forms['bookingform' + fleetID];
oFormElement = oForm.elements['startdate'];
oFormElement.value = startDate;
..开发者_开发问答.but get the error "oForm.elements is null or not an object".
Until now I have been using document.getElementById('startdate').value instead of creating a forms object. Which is the correct approach when specifying which form the value should populate?
form.elements is a plain array. So either you know the index or you have to search for it.
Form = document.forms['bookingform' + fleetID];
oFormElement = oForm.elements[0]; // This is the index of the element
oFormElement.value = startDate;
If you have to search then it's like this:
Form = document.forms['bookingform' + fleetID];
var oFormElement;
for (var i = 0, len = oForm.elements.length; i < len; ++i) {
if (oForm.elements[i].name == "startdate") {
oFormElement = oForm.elements[i];
break;
}
}
if (oFormElement) {
oFormElement = oForm.elements[0]; // This is the index of the element
oFormElement.value = startDate;
} else {
// crash
}
精彩评论