I just can't figure out how to get the name and value of the passed object
I have a show function, basically it is displaying the nodes and attributes of my xml. I created object attributes to store the name and value of each attribute. This part works well. Now when I pass this object to another function, I just can't get the name and value of the attributes. It says that aname and avalue are undefined. Can anyone please help?
My code:
function show(){
:
var mytag2 = child.nodeName;
var mytagvalue2 = child.textContent;
var attributes = [];
for (var k = 0; k < child.attributes.length; k++) {
var attrib = child.attributes[k];
if (attrib.specified === true) {
attributes.push({aname: attrib.name, avalue: attrib.value});
$("#maincontent").append("<li>" + attributes[k].aname + " = " +
attributes[k].avalue + "</li>");
}
}
$("#maincontent").append("<td><button id=\"popup\" onclick=\"div_show('" + mytag2 + "','" + mytagvalue2 + "','" + attributes + "')\">Edit</button></td><td></td></tr>");
}
function div_show(tag, tcontent, attributes){
for (i = 0; i < attributes.length; i++) {
var target = document.getElementById('attributes');
target.innerHTML = '';
target.innerHTML += "<input id=" + "'" + attributes[i].aname + "'" + " " +
"type = text" + " " + "name=" + "'" + attributes[i].aname + "'" + ">";
document.getElementById("'" + attributes[i].aname + "'").value =
attributes[i].aname;
document.getElementById("'" + attributes[i].avalue + "'").value =
attributes[i].avalue;
}
}
source to share
Without getting into a discussion about why you should do this all differently, I'll point out the problem and how you fix it.
In your code, you create a line:
$("#maincontent").append("<td><button id=\"popup\" onclick=\"div_show('" + mytag2 + "','" + mytagvalue2 + "','" + attributes + "')\">Edit</button></td><td></td></tr>");
attributes
is an array object and this will call a method toString()
on it to bind it to the string that is being built. This will make it like [object Object]
.
You have to serialize it to JSON and concatenate that instead (also remove the quotes around the string as you want to pass your array object).
$("#maincontent").append("<td><button id=\"popup\" onclick=\"div_show('" + mytag2 + "','" + mytagvalue2 + "'," + JSON.stringify(attributes) + ")\">Edit</button></td><td></td></tr>");
This will create a string that looks like the array you want to pass:
[{"aname":"someName","avalue":"someValue"}]
Here's a simplified example that shows what I'm talking about:
var attributes = [
{ aname: 'test1', avalue: 'test1' },
{ aname: 'test2', avalue: 'test2' }
];
var arrayConcatenated = 'Array Concatenated: ' + attributes;
var arrayJSONConcatenated = 'Array JSON Concatenated: ' + JSON.stringify(attributes);
document.getElementById('arrayConcatenated').innerHTML = arrayConcatenated;
document.getElementById('arrayJSONConcatenated').innerHTML = arrayJSONConcatenated;
<div id="arrayConcatenated"></div>
vs.
<div id="arrayJSONConcatenated"></div>
source to share