admin管理员组文章数量:1279015
I have a code 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>
ouput error: document.form is undefined, how to fix it ?
I have a code 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>
ouput error: document.form is undefined, how to fix it ?
Share Improve this question asked Jan 17, 2012 at 9:58 user1099407user1099407 04 Answers
Reset to default 3The form property of document
does not exist. You're probably confused with the document.forms
HTML collection:
document.forms[0]; //First <form> element
document.forms['name_of_form']; //Points to <form name="name_of_form">
Fixed code:
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);
}
Just define the name parameter in the form tag like < form name="form1" ...> and call it through array value as below.
e.g var type = document.form1.type[i].value;
There is no property document.form
.
document
has a property forms
which is an array of the forms the document contains. You access the desired form this way:
document.forms[0] // first form
document.forms['theForm'] // form with name="theForm"
document.form
is not standard as far as I know. document.forms
(note the 's') is. Documents can have multiple forms.
本文标签: Error documentform is undefined in javascriptStack Overflow
版权声明:本文标题:Error document.form is undefined in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741241427a2364053.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论