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 0
Add a ment  | 

4 Answers 4

Reset to default 3

The 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