简体   繁体   中英

Why does this give “undefined” error?

I am trying to get the user to put something into the text area and the output should be what he wrote repeapiting x amount of times, but I get an error "document.forme is undefined".

Can you please help me understand why it is undefined?

My code:

 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>input home work</title>
<script type="text/javascript">


 var help= document.forme.tryout.value;

 for (x=1; x<=10;x++){

 function numberCheak (){

     document.write("this is"+"  "+help++);

     }


 }
  </script>


  </head>

 <body>
<form name="forme">

<input name="tryout" type="text" />
  <input type="button" value="click me" onClick="numberCheak();"/>


</form>

</body>
</html>

Ok, you have a few problems. The first is that you are trying to access a form element that doesn't exist yet: the script is above the form element, so the form doesn't exist when you try to get it. If you move the script to the bottom of the page it will work better.

Second, the loop should be inside the function, not wrapped around the function.

Third, document.write has weird side effects and causes the document to be rewritten and will stop the script from continuing correctly.

Here's my revised script

function numberCheak() {
    var help = document.forme.tryout.value;
    for (var x = 1; x <= 10; x++) {
        document.getElementById("output").innerHTML += help;
    }
}

and the HTML form that goes with it

<form name="forme" id="forme">
    <input name="tryout" type="text" /> 
    <input type="button" value="click me" onclick="numberCheak();" /> 
    <span id="output"></span>
</form>

You can see it in action on jsFiddle.

Forms are stored in collection and can be accessed like this:

var form = document.forms[i]; or var form = document.forms[name];

In your case, i is 0 and name is forme.

也许您应该尝试使用document.getElementsByName("forme")[0]而不是document.forme吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM