javascript中未定义错误document.form
Error document.form is undefined in javascript
我有一个代码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")是。文档可以有多种形式。
相关文章:
- 正在寻找比$(document).ready慢的$(window).load的替代方案
- document.open/document.write没有正确地清除chrome中的文档——这是chrome的错误吗
- 如何用更合适的内容替换document.write
- 如何解决document.createelement('form').submit和&submi
- Document.form.submit() 不起作用
- onclick=“document.forms[0].submit();” 和 form submit 之间的区别
- 在 document.form.element.value 上触发 jquery
- this.form 和 document.forms 之间的区别
- 为什么我们在 JavaScript 中使用 document.form[0] 而不是 document.form[1(o
- 将变量传递给JavaScript函数并在document.form中使用它
- 这可能吗:document.form.array[i].value
- Javascript document.form.submit() not working
- javascript中未定义错误document.form
- javascript文件.form[0]和document.
有不同的元素 - 在使用document.form.action提交之前检查值
- 如何在onchange="document.my-form.sumbit"时追加URL
- 是否有document.form.submit()的替代方法?
- document.form[0]在Firefox上不起作用
- 如何从document.form获得html元素
- Internet Explorer 8 - Javascript document.form.submit() 不适用于