I have an array and branch_id that I want to pass to javascript add table row with onclick function.
var branch_id = 1;
var member_data= [];
member_data.push({
phone: 123,
name: "aaa",
id: 3,
});
member_data.push({
phone: 456,
name: "bbb",
id: 4,
});
addrow(branch_id ,member_data)
Pass data and array to addrow function, and set array as the parameter in onclick function. When click on the Show button, it will show all the array data
function addrow(branch_id, member_data){
console.log(member_data)//able to read array
var table = document.getElementById("itemTable");
var tableRow = table.rows.length;
var row = table.insertRow(tableRow);
var cell1 = row.insertCell(0);
cell1.innerHTML =
'<button type="button" onclick="show_member(member_data)">Show</button>'//this line of show "member_data is not defined"
+ '<input type="text" name="branch" value="'+branch_id+'">';
}
function show_member(member_data){
for (var i = 0; i < member_data.length; i++) {
alert(member_data[i]);
}
}
But I am unable to pass the array to the onclick, it show "member_data is not defined". Isn't possible to pass array to onclick function
member_dataavailable on console?name: bbb,should bename: "bbb", same forname: aaa, they're being interpreted as identifiers, not strings.member_datavariable, it won't be available globally. For example, if thisvar member_datais inside a function, this will not be accessible in to onClick. You must do somethin likewindow.member_data = ...or declare it outside the function.