• Welcome to The Cave of Dragonflies forums, where the smallest bugs live alongside the strongest dragons.

    Guests are not able to post messages or even read certain areas of the forums. Now, that's boring, don't you think? Registration, on the other hand, is simple, completely free of charge, and does not require you to give out any personal information at all. As soon as you register, you can take part in some of the happy fun things at the forums such as posting messages, voting in polls, sending private messages to people and being told that this is where we drink tea and eat cod.

    Of course I'm not forcing you to do anything if you don't want to, but seriously, what have you got to lose? Five seconds of your life?

Javascript type error: variable supposedly undefined even though I've initialised it

myuma

Flowers. So many of the same. So many unneeded.
Pronoun
they/them
Hey, I made a rudimentary quiz script a while back and recently unearthed it to use on my site. It's the type of quiz where each combination of answers gives a unique result.

Here it is:

var FORM_NAME = "form"; //set to name of form
var form = document.forms[FORM_NAME];
var result_div = document.getElementById("result");
var image = document.getElementById("image");
var desc_title = document.getElementById("desc-title");
var desc_main = document.getElementById("desc-main");
var i;

form.onsubmit = function(){
var chosen_result = "";
var temp;
var inputs = document.forms[FORM_NAME].elements;
for (i = 0; i < (inputs.length); i++) {
temp = inputs;
if((temp.checked)){
chosen_result += temp.value;
}
}

//image.src = results[chosen_result].image;

desc_title.innerHTML = results[chosen_result].name;

desc_main.innerHTML = results[chosen_result].text;

result_div.style.display = 'block';

return true;

As you can see, I've initialised form here: var form = document.forms[FORM_NAME];
FORM_NAME
has been set to the correct thing; it's identical to what I put in the HTML, so I'm not sure why I'm being told form is undefined...
I know the rest of the code works because back when I first made it, it did correctly calculate results and put them on the page.
Any help would really be appreciated!
 
Last edited:

IndigoEmmy

Is a cat meow
Pronoun
she/her
:unsure:
Maybe you spelled something wrong? Or have a duplicate of the same thing that's confusing the code? You probably already checked this, but this is what i always do when i come across a problem.
 

kokorico

cooped up
Pronoun
e/em
document.forms is numerically indexed - like an array, not an object. So your forms will be things like document.forms[0], document.forms[1] etc., not document.forms["form"].

If you want to use the form's name instead, you've got a couple of options. You could give the form an id attribute as well as a name, and use document.getElementById(). Or if you know how to use CSS selectors, you could do something like this:
JavaScript:
var form = document.querySelector('form[name="form"]');
 
Last edited:

kokorico

cooped up
Pronoun
e/em
Huh, I was looking right at the MDN page and somehow just completely blanked that section, lol.

In that case we probably need to see the associated HTML in order to be any more help, myuma

edit: great minds think alike, it seems
I wanted to say "birds of a feather flock together" but it didn't quite fit :'(
 
Last edited:

Eifie

oh man, good times.
Pronoun
she/her
The most likely explanation is that there isn't actually a form with the given name at the time you're assigning that variable, so indexing into the table with that name just gives you undefined.

You could try adding console.log(document.forms); right before the variable assignment and then checking its value in the JavaScript console to verify.
 

myuma

Flowers. So many of the same. So many unneeded.
Pronoun
they/them
Here's the relevant HTML:

<form id= "form">

<p><b>Would you want to live in a modern area, or a historic one?</b></p>
<label><input type= "radio" name="q1" value="Modern">Modern</label>
<label><input type= "radio" name="q1" value="Historic">Historic</label>

<br>
<p><b>What kind of lifestyle would you want?</b></p>
<label><input type= "radio" name="q2" value="Fast">Fast-paced: There's always something happening</label>
<label><input type= "radio" name="q2" value="Slow">Laid back: It's relaxed and calm</label>

<br>
<p><b>Would you want to live somewhere urban, or natural?</b></p>
<label><input type= "radio" name="q3" value="Urban">Urban: In a town or city, close to other people</label>
<label><input type= "radio" name="q3" value="Natural">Natural: Might be more remote, but close to forests or coasts</label>
<br>

<p><b>Out of these two, what kind of facilities would you want available?</b></p>
<label><input type= "radio" name="q4" value="Museum">Museums, safaris, research labs</label>
<label><input type= "radio" name="q4" value="Mall">Shopping malls, lotteries, sports stadiums</label>
<br>

<p><button type="submit">Where's my home?</button></p>
<br>
</form>

<div id= "result" style = "display: none;">
<h3 id= "desc-title"></h3>
<p id= "desc-main"></p>
</div>

I originally wrote <form name= "form"> but it still comes up as undefined after I changed it to use id.

Quick edit - also, I stuck console.log(document.forms) in there and it returned the name of the form alright. This makes me think the problem isn't the HTML.

After some more fiddling: I don't know why I didn't check this earlier, but according to the console the error occurred on this line: form.onsubmit = function(){

So maybe I'm defining the function incorrectly.
 
Last edited:

Butterfree

Still loves Joltik, though!
Staff member
Pronoun
she/her
You need a name on the form for it to be named in document.forms, not an ID.
 

Eifie

oh man, good times.
Pronoun
she/her
Here's the relevant HTML:

<form id= "form">

<p><b>Would you want to live in a modern area, or a historic one?</b></p>
<label><input type= "radio" name="q1" value="Modern">Modern</label>
<label><input type= "radio" name="q1" value="Historic">Historic</label>

<br>
<p><b>What kind of lifestyle would you want?</b></p>
<label><input type= "radio" name="q2" value="Fast">Fast-paced: There's always something happening</label>
<label><input type= "radio" name="q2" value="Slow">Laid back: It's relaxed and calm</label>

<br>
<p><b>Would you want to live somewhere urban, or natural?</b></p>
<label><input type= "radio" name="q3" value="Urban">Urban: In a town or city, close to other people</label>
<label><input type= "radio" name="q3" value="Natural">Natural: Might be more remote, but close to forests or coasts</label>
<br>

<p><b>Out of these two, what kind of facilities would you want available?</b></p>
<label><input type= "radio" name="q4" value="Museum">Museums, safaris, research labs</label>
<label><input type= "radio" name="q4" value="Mall">Shopping malls, lotteries, sports stadiums</label>
<br>

<p><button type="submit">Where's my home?</button></p>
<br>
</form>

<div id= "result" style = "display: none;">
<h3 id= "desc-title"></h3>
<p id= "desc-main"></p>
</div>

I originally wrote <form name= "form"> but it still comes up as undefined after I changed it to use id.

Quick edit - also, I stuck console.log(document.forms) in there and it returned the name of the form alright. This makes me think the problem isn't the HTML.

After some more fiddling: I don't know why I didn't check this earlier, but according to the console the error occurred on this line: form.onsubmit = function(){

So maybe I'm defining the function incorrectly.
I doubt it has to do with the function; you're trying to set the onsubmit property of something undefined, which raises an error. (btw, is it supposed to be onSubmit? I'm not sure about vanilla JavaScript)
 

kokorico

cooped up
Pronoun
e/em
After changing the id="form" back to name="form", your code works for me. (It doesn't actually do anything, but it gets through the problematic line without throwing an error.) So I suspect the problem may be somewhere else.

I've put it online here - can you take a look at the page source code and see if you can spot anything different from your version?
 

myuma

Flowers. So many of the same. So many unneeded.
Pronoun
they/them
kokorico:
Thanks, that seems like a lot of effort you went to! I decided to stick the versions into a text comparison tool because I suck at noticing small details. Other than the opening form tag using name instead of id, the differences it picked up were very small, things like extra spaces/newlines after tags and stuff. The error did not go away after removing those.

So I suspect the problem may be somewhere else.
I'm wondering if it's something to do with my computer and/or browser, which are both pretty old. But seeing as Javascript is executed client-side and your version works fine when I view it, that probably isn't it. I'm at a loss what to do next.

Eifie:
I checked and it is all lowercase. Staying on guard for typos though. :P
 
Last edited:

myuma

Flowers. So many of the same. So many unneeded.
Pronoun
they/them
Firefox 45... but it's pretty basic Javascript which an old browser should definitely be able to handle. >:/
 

IndigoEmmy

Is a cat meow
Pronoun
she/her
Hmm... In that case i have absolutely no clue because my knowledge of this stuff is fairly limited. I really do hope you find a solution.
 

myuma

Flowers. So many of the same. So many unneeded.
Pronoun
they/them
Here you go.
A few minor things on it are different to what I originally put in the OP, but it still has the same problem.
 

kokorico

cooped up
Pronoun
e/em
Aaaah, I get it! Your problem is that the <script> tag is at the very beginning of the document, so it runs before the <form> appears on the page.

The simplest way to get it running in the right order would be to move the <script> tag to the end of the document, like this:
HTML:
<!-- the rest of your page goes above here -->

<div id= "footer">
<p>This is not an official website. The Pokemon franchise belongs to Gamefreak, The Pokemon Company, Creatures Inc., and Nintendo, 1995 - 2020. Otherwise, the content of this website belongs to me, myuma/lapi.</p>
</div>

<script src= "js/town-quiz/ideal-town-quiz.js" type= "text/javascript"></script>
</body>
</html>
A slightly more fancy way of doing it would be to set up an event listener, like this:
JavaScript:
window.addEventListener('load', function() {

    // the rest of your JavaScript code goes in here

});
That basically tells the browser to wait until the page has finished loading before running your code.
 

Eifie

oh man, good times.
Pronoun
she/her
That was why I suggested putting the log statement right before the variable assignment... weird that the form was present in the output. :unsure:
 

myuma

Flowers. So many of the same. So many unneeded.
Pronoun
they/them
It's been solved! Thanks so much everyone! :'D

Time to go do some fixing then, and also some learning about web programming. I found the answers to this stackoverflow question, which go into more detail about when & where to place script tags in your HTML, pretty useful in that regard.
 
Top