WhatTheCode
WhatTheCode

Reputation: 57

Uncaught TypeError: Cannot read property 'checked' of undefined Javascript

The first time the loop runs, there's no problem. The get's shown when the loop ends, and every other time the loop runs. The .checked property works fine, to my knowledge, there's just the error... Does someone know what to do about this? My background in javascript isn't that broad, and I'm still learning. Thanks you.

I have already tried .checked === true and .checked == checked ...

In the code snippet below dishes is an array of radiobuttons.

    for (i = 0; i <= dishes.length; i++) {
       if (dishes[i].checked) {
         switch (dishesClass) {
        .........
         }
       }
     }

I expect no error in the console, but there are multiple. Every time the loop ends, the console states the same error.

Uncaught TypeError: Cannot read property 'checked' of undefined

Upvotes: 0

Views: 204

Answers (2)

Rov
Rov

Reputation: 133

As pointed by @Alicia, the problem is in your loop condition i<= whereas it should be i<. The array index i tries to access an element outside of the array bounds on the last iteration. Array's index starts at zero and ends at the array length - 1

Upvotes: 0

Alicia Sykes
Alicia Sykes

Reputation: 7127

In your for loop you are testing if i is less than or equal to dishes.lengh. You just need to check if it is less than, since i starts from 0, as does array indexes in computing.

So just replace i <= dishes.length; with i < dishes.length;

Hope that helps

This code will work

for (i = 0; i < dishes.length; i++) {
   if (dishes[i].checked) {
     switch (dishesClass) {
    .........
     }
   }
 }

This resource, on Loops and Iteration may help you.

Upvotes: 1

Related Questions