javascript中未定义错误document.form

Error document.form is undefined in javascript

本文关键字:document form 错误 未定义 javascript      更新时间:2023-09-26

我有一个代码javascript:

<form onsubmit="return false;" action="">
<input type="radio" name="type" id="type0" value="0" onclick="toggleSet(this)" checked />type 0
<input type="radio" name="type" id="type1" value="1" onclick="toggleSet(this)" />Type 1
</form>
<script>
function toggleSet() {
    for(var i=0; i<document.form.type.length; i++) {
        if(document.form.type[i].checked) {
            var type = document.form.type[i].value;
        }
    }
    alert(type);
}
</script>

输出错误:document.form未定义,如何修复?

document的表单属性不存在。您可能对document.forms HTML集合感到困惑:

document.forms[0];              //First <form> element
document.forms['name_of_form']; //Points to <form name="name_of_form">

固定代码:

function toggleSet() {
    var form = document.forms[0];
    var type; //Declare variable here, to prevent a ReferenceError at the end
    for(var i=0; i<form.type.length; i++) {
        if(form.type[i].checked) {
            type = form.type[i].value;
            break; // After finding an occurrence, break the loop:
                   // You expect only one value
        }
    }
    alert(type);
}

只需在表单标记中定义name参数,如<表单名称=";form1">并通过数组值调用它,如下所示。

例如var type=document.form1.type[i].value;

没有属性document.form

document具有属性forms,该属性是文档包含的表单的数组。您可以通过以下方式访问所需表单:

document.forms[0] // first form
document.forms['theForm']  // form with name="theForm"
就我所知,

document.form不是标准配置。document.forms(注意"s")是。文档可以有多种形式。