As there is no CreateHtmlNode
available, you will need to use .innerHTML
instead.
I altered your function, adding an additional parameter expecting an object with the fields "linkField" (target holding the link) and "urlField" (Hyperlink field in the JSON response):
function createTableWithLink(tbody, data, field, urlInfo) {
var texto;
for (var i = 0; i < data.length; i++) {
var row = document.createElement("tr");
tbody.appendChild(row);
for (var j = 0; j < field.length; j++) {
var cell = document.createElement("td");
if (field[j] === urlInfo.linkField) {
cell.innerHTML = '<a href="' + data[i][urlInfo.urlField] + '">' +
data[i][field[j]] + '</a>';
} else {
cell.innerHTML = data[i][field[j]];
}
row.appendChild(cell);
}
}
}
createTableWithLink(
document.getElementById("senate-data"), data.results[0].members,
["first_name", "party", "state", "seniority", "votes_with_party_pct"],
{
linkField: "first_name",
urlField: "url"
}
);
Here is a Fiddle showing the change.
General note:
As you are a beginner, I hope you don't mind words of advise. I would recommend to stick to ending your lines with a semi-colon, even if it's not required. Also take care of the indentation of your lines as this will help both you and your team members to get into the code more quickly. Well structured code is beautiful :-)
Answers to your questions in comments:
1.) Additional object as parameter:
In Javascript Objects are contained in {}
and contain field and values in the form of fieldName: "value"
(or "fieldName": "value"
as it is required in JSON). Objects can be structured very freely and can contain other Objects, arrays or simple arrays.
Here's a bit of reading showing different ways to initialize objects.
There is way more to tell about Objects but that should be it for the beginning.
I personally like to define groups of varriables inside objects as this allows me to access the variables contained via its given names, e.g. as urlInfo.linkField
in the createTableWithLink()
method. If I had used an array instead, this would have been something like urlInfo[0]
instead in case I had used a numeric key array.
2.) Using var linkField = getElementById("first_name")
instead:
First of all: getElementById(ELEMENT)
will simply return the object with the given ID from the current HTML document so in our case where we are working with a JSON structure containing all the data it would simply not fit.
In case you would have a button that loads the JSON, then you could define two input fields for the URL and link column in the JSON response dynamically and add these as parameters:
<label>Link to be added to: <input type="text" id="link_field" value="first_name"/></label>
<label>Field should be linked to: <input type="text" id="url_field" value="url"/></label>
<input type="button" onclick="createTableOnButtonClick()" value="Create table"/>
// call the original function, pass in the values from the input fields:
function createTableOnButtonClick() {
createTableWithLink(
document.getElementById("senate-data"), data.results[0].members,
["first_name", "party", "state", "seniority", "votes_with_party_pct"],
{
linkField: document.getElementById("link_field").value,
urlField: document.getElementById("url_field").value
}
);
}
If you don't require any dynamic definition of the fields, you can always hard-code values and checks inside your function but I would advise against it as you also pass in the fields dynamically. Just for completeness this would be a version of the function with hard-coded checks:
// the URL definition parameter has been reduced as they are now hard-coded
function createTableWithLink(tbody, data, field) {
var texto;
for (var i = 0; i < data.length; i++) {
var row = document.createElement("tr");
tbody.appendChild(row);
for (var j = 0; j < field.length; j++) {
var cell = document.createElement("td");
// hard-coded checking for field "first_name"
if (field[j] === "first_name") {
cell.innerHTML = '<a href="' + data[i]["url"] + '">' +
data[i]["first_name"] + '</a>';
...
3.) When to use square brackets ([]
) or dot-syntax (.property
)?
Arrays are a special type of object so you may access arrays as well with "Property accessors".
Here is a very good Stack Overflow Q&A about accessing objects and arrays using different notations.
Basically you can always use the property accessor if you have a key in the form of a string but you can always use array accessors independent of the index type:
var numArr= [20, "Test"];
var stringArray= [];
stringArray["testValue"]= "4711";
stringArray["anotherValue"]= "0815";
console.log(numArr[0]);
console.log(stringArray.testValue);
console.log(stringArray["anotherValue"]);
// won't work:
console.log(numArr.0);