Suman r Suman r - 1 year ago 55
jQuery Question

issue in for loop when using dynamic loop of array in javascript Uncaught TypeError: Cannot read property 'id' of undefined at saveSign

I got the below error in this code in for loop but when i give iput+=checkedBoxes[1].id staticaly means it is working please help and also alert in for loop is working with s


ERROR : Uncaught TypeError: Cannot read property 'id' of undefined at saveSign


function saveSign(){
alert('asd')
var iput =[];
var checkedBoxes = document.querySelectorAll('input[type=checkbox]');
for (var s=1;s<=checkedBoxes.length;s++){
iput+=checkedBoxes[s].id
}
console.log(iput)
}

Answer Source

The problem has to do with your for loop's loop counter. It starts at 1, skipping the first array element, then proceeds up to the length, at which index in the array exists no element. You can avoid loop counters altogether with a for-of loop or a forEach callback.

I also noticed you were using the += operator on an array (iput). To append elements to an array, you use the push method. If you wanted a string, set iput to an empty string ('') and keep the +=.

Lastly, you omitted a few semicolons. With the pitfalls of automatic semicolon insertion, it's easier to just use them whenever possible to avoid unexpected behavior.

Using a normal for loop:

function saveSign() {
   const iput = [];
   const checkedBoxes = document.querySelectorAll('input[type="checkbox"]');
   for(let i = 0; i < checkedBoxes.length; i++) {
     iput.push(checkedBoxes[i].id);
   }
   console.log(iput);
}

Using a for-of loop:

function saveSign() {
   const iput = [];
   const checkedBoxes = document.querySelectorAll('input[type="checkbox"]');
   for(const checkedBox of checkedBoxes) {
     iput.push(checkedBox.id);
   }
   console.log(iput);
}

Using a forEach callback:

function saveSign() {
   const iput = [];
   const checkedBoxes = document.querySelectorAll('input[type="checkbox"]');
   checkedBoxes.forEach((checkedBox) => {
     iput.push(checkedBox);
   });
   console.log(iput);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download