Reputation: 69
When I pass an array of strings and an index to an onclick event, the callback function receives the parameters from the first two values of the array as a number instead of the array and the index.
I have tried to convert it to an array using the Array.from function.
let presentantes = ["28411", "199904", "214966", "16226"];
console.log('presentantes', presentantes);
//presentantes (4) ["28411", "199904", "214966", "16226"]
let id = 1
let listNominated = `<li onClick="cargaPresentantes(${presentantes}, ${i})">`
function cargaPresentantes(presentantes, id) {
console.log('presentantes', presentantes);
console.log('id', id)
//presentantes 28411
//id 199904
}
I was expecting to get an array ["28411", "199904", "214966", "16226"]
and the index 1
Upvotes: 1
Views: 1017
Reputation: 69
As Andrea said I had to add an onclcik listener function. To do this, I had to append the string literal to the document first.
Upvotes: 0
Reputation: 29
Actually template literals work something like this - If the variable which is passed to the placeholder is not a string(an array in this case) then it CONVERTS it to string. So in your code the value of listNominated becomes '28411,199904,214966,16226,1' and thus it takes the first two arguements i.e. 28411 and 199904.
Upvotes: 1
Reputation: 194
You cannot pass the parameters in that way... you should create a “onclick listener function” and then associate it to the “li” element.
Upvotes: 0