" <input value=\"gng(9,5)\">"
is considered a string in programming, meaning it is simply literal text data. The inclusion of
gng(9,5)
within the string does not trigger the function
gng
. To properly incorporate the result of
gng(9,5)
, you must concatenate the surrounded parts of the string with an invocation like so:
' <input value="' + gng(9,5) + '">'
. In this revised version, I have switched the double quotes to single quotes which are interchangeable in JavaScript – using single quotes eliminates the need to escape double quotes inside the string.
Here is the modified code block:
function gng(a, b) {
var c = a / b;
return c;
}
var tbl = document.createElement('table');
var tr = [];
var td = [];
var i; // ensure all variables are declared!
var s; // note that without declaring s and i, they become implicit globals
var rowcount = 5;
var columncount = 3;
var dataarray = [
["1", "red", ' <input value="' + gng(9,5) + '">'],
["2", "white", ' <input value="' + gng(3,5) + '">'],
["3", "black", ' <input value="' + gng(4,5) + '">'],
["4", "green", ' <input value="' + gng(1,5) + '">'],
["5", "gray", ' <input value="' + gng(2,5) + '">']
];
for(s = 0; s < rowcount; s++) {
tr[s] = document.createElement('tr');
for(i = 0; i < columncount; i++) {
td[i] = document.createElement('td');
td[i].innerHTML = dataarray[s][i];
tr[s].appendChild(td[i]);
}
tbl.appendChild(tr[s]);
}
document.getElementById('yeni').appendChild(tbl);
<div id="yeni" style="position: absolute; top: 50px; left: 30px; width: 700px; height: 400px; "> </div>
If your target browsers support template literals, you can use them instead:
["1", "red", `<input value="${gng(9,5)}">`],
In my approach, I would opt for a slight variation by utilizing the forEach method
on the array of data rather than a traditional for loop
:
function gng(a, b) {
var c = a / b;
return c;
}
var tbl = document.createElement('table'),
dataArray = [
["1", "red", ' <input value="' + gng(9,5) + '">'],
["2", "white", ' <input value="' + gng(3,5) + '">'],
["3", "black", ' <input value="' + gng(4,5) + '">'],
["4", "green", ' <input value="' + gng(1,5) + '">'],
["5", "gray", ' <input value="' + gng(2,5) + '">']
];
dataArray.forEach(function (row) {
var tr = document.createElement('tr');
row.forEach(function (data) {
var td = document.createElement('td');
td.innerHTML = data;
tr.appendChild(td);
});
tbl.appendChild(tr);
});
document.getElementById('yeni').appendChild(tbl);
<div id="yeni" style="position: absolute; top: 50px; left: 30px; width: 700px; height: 400px; "> </div>
This alternative method simplifies the code, enhances readability, and improves maintainability for future adjustments as there's no longer a manual requirement to update column and row counts if the data array changes.