0

So I have an array items, that always has 7 columns. Using the code provided, I can display each element of the array with out error. However when I try to access the array at the end like this:

<button onclick="delete_item(items[i][6])">Delete</button>

I get:

Uncaught TypeError: Cannot read property '6' of undefined
    at HTMLButtonElement.onclick (account.php:64)
onclick @ account.php:64

Rest of my code is:

for(i=0;i<items.length;i++){
                document.write('<div style="border-style:solid;padding:15px;background-color:whitesmoke;"><img src="'+items[i][5]+'" style="width:8%"><br><b style="font-size:20px;">'+items[i][0]+'</b><br>$'+items[i][1]+'<div style="float:right"><a href="item.php?itemid='+items[i][6]+'&itemname='+items[i][0]+'" style="font-size:20px">Click Here for the Item Information</a></div><br>Seller: '+items[i][2]+'<br>Description: '+items[i][3]+'<br> <button onclick="delete_item(items[i][6])">Delete</button></div>');
document.write('<br>');
                }

Also, by using <button onclick="delete_item(items[1][6])">Delete</button> instead of using 'i', everything works fine. What would cause this, because shouldn't using i

Tony Cicero
  • 75
  • 1
  • 7

2 Answers2

0

Use this below one because in your code snapshot, I not referring index. Its trey to read I kay from your array and that not available, try below code:

<button onclick="delete_item(items["+i+"][6])">Delete</button>
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
0

You have to add some quotes around your variable:

'<button onclick="delete_item(\''+items[i][6]+ '\')">Delete</button>'

let a = ["a","b","c","d","e","f","g"];
let b = ["x","b","c","d","e","f","y"];

let items = [a,b];

var delete_item = function(item){
 console.log("delete: " + item)
}

for (i = 0; i < items.length; i++) {
  document.write('<div style="border-style:solid;padding:15px;background-color:whitesmoke;"><img style="width:8%"><br><b style="font-size:20px;">' + items[i][0] + '</b><br>$' + items[i][1] + '<div style="float:right"></div><br>Seller: ' + items[i][2] + '<br>Description: ' + items[i][3] + '<br> <button onclick="delete_item(\''+items[i][6]+ '\')">Delete</button></div>');
  document.write('<br>');
}

Also, you could consider using document.createElement and addEventListener.

eag845
  • 1,013
  • 1
  • 11
  • 16