0

I'm trying to make a result generator for students based on their enrollment numbers. I'm new to stackoverflow and also a beginner JS programmer, so forgive me.

Whenever I click the button in the form it throws up this error:

TypeError: Cannot read property 'length' of undefined at HTMLButtonElement.displayInfo (index.js:21)

let info = {
  student: [{
      enrollNo: '6773',
      name: 'Joe',
    },
    {
      enrollNo: '6774',
      name: 'Ben',
    },
  ],

  DOM: {
    body: document.body,
    form: document.querySelector('form'),
    nameRow: document.querySelector('#nameRow'),
    submitBtn: document.querySelector('#submit'),
  },

  displayInfo: function() {
    for (let i = 0; i < this.student.length; i++) {
      if (this.DOM.nameRow.value == this.student[i].enrollNo) {
        let name = document.createTextNode(this.student[i].name);
        const name_h1 = document.createElement('h1');

        name_h1.appendChild(name);

        this.DOM.body.appendChild(name_h1);
        break;
      }
    }
  },
};

info.displayInfo();

info.DOM.submitBtn.addEventListener('click', info.displayInfo);
<form onsubmit="event.preventDefault();">
  <input type="text" id="nameRow" />
  <button id="submit">Check</button>
</form>
Rodrigo
  • 96
  • 1
  • 1
  • 7
  • 1
    student property is on info object `info.student` – Vikas Sep 30 '20 at 13:52
  • I was writting answer and someone closed it. Anyway, here is [fiddle with solution](https://jsfiddle.net/3yrmjkne/) – m51 Sep 30 '20 at 14:10
  • @m51 Thanks for the solution mate! I opted for the arrow function method with 'info.student.length' thingie. Apologies, I'm a new programmer. :( – inshalkhan03 Sep 30 '20 at 14:29

0 Answers0