1

Console is saying " Cannot read property 'checked' of undefined "

I have radio buttons which I'm using for a questionnaire and based on the persons answer it gives them a mark and at the end I've to calculate all the marks together and give them a particular message depending on the range of which there score falls into.

I've played around with the brackets checking to see did a make an error and checked that the radio buttons were labelled correctly.

//javascript function that is having the issue

function calcSecThree(){

    var total = 0;
        for(var i=1; i <= 2; i++) {
            for(var x = 0; x < 5; x++) {                    
                if(document.getElementsByName('3.' + i)[x].checked){
                    total += x + 1;
                        }
                }
            }
      alert("total is "+total);
};

I expect there to be an alert appearing with the total that is displaying. It is working for the previous two sections however I'm getting errors with this section for some reason

No alert is appearing and when i check the console I am getting the error -

"Cannot read property 'checked' of undefined"

2
  • 1
    document.getElementsByName('3.' + i)[x] is undefined for one of the entries. Commented May 8, 2019 at 16:23
  • To debug, try to log to console all document.getElementsByName('3.' + i) occurences. Commented May 8, 2019 at 16:43

2 Answers 2

1

you should put a check to see if the element exists then run the next if condition to avoid error

function calcSecThree() {

  var total = 0;
  for (var i = 1; i <= 2; i++) {
    for (var x = 0; x < 5; x++) {
      if (document.getElementsByName('3.' + i)[x]) {
        if (document.getElementsByName('3.' + i)[x].checked) {
          total += x + 1;
        }
      }
    }
  }
  alert("total is " + total);
};
Sign up to request clarification or add additional context in comments.

Comments

0

I think this element does not exists on DOM.

document.getElementsByName('3.' + i)[x].checked

Please inspect this element value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.