我的网页上有多个使用 JavaScript 创建的表单,我想用值 (startDate) 填充相应表单中的字段。
我尝试过以下代码:
oForm = document.forms['bookingform' + fleetID];
oFormElement = oForm.elements['startdate'];
oFormElement.value = startDate;
...但是收到错误“oForm.elements 为 null 或不是对象”。
到目前为止,我一直在使用 document.getElementById('startdate').value 而不是创建表单对象。指定值应填充哪种形式时,哪种方法是正确的?
最佳答案
form.elements 是一个普通数组。因此,要么您知道索引,要么必须搜索它。
Form = document.forms['bookingform' + fleetID];
oFormElement = oForm.elements[0]; // This is the index of the element
oFormElement.value = startDate;
如果你必须搜索,那就像这样:
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
}
关于JavaScript 表单规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4796696/