Reputation: 482
I have some code which loops through an array and adds the data to a HTML table.
For one of the fields 'Unit_Sell', I would like to prefix the HTML with a '£' symbol.
Here is what I have tried.
for (var i = 0; i < arr.length; i++) {
var node = win.document.createElement("tr")
for (var key of ['description', 'ref_date_start', 'ref_date_end', 'unit_sell', 'qty', 'price']) {
var tb = win.document.createElement("td")
if (key = 'unit_sell') {
tb.innerHTML = '£' + arr[i][key]
}
tb.innerHTML = arr[i][key]
tb.style.paddingLeft = "30px";
node.appendChild(tb)
}
}
The loop works fine, but the if statement condition is not being met.
Upvotes: 0
Views: 49
Reputation: 10873
As pointed out already you need to compare key
to 'unit_sell'
instead of assigning. However you also need an else
branch, otherwise the innerHTMl
from within the condition will be overwritten.
for (var i = 0; i < arr.length; i++) {
var node = win.document.createElement("tr")
for (var key of ['description', 'ref_date_start', 'ref_date_end', 'unit_sell', 'qty', 'price']) {
var tb = win.document.createElement("td")
if (key === 'unit_sell') {
tb.innerHTML = '£' + arr[i][key]
} else {
tb.innerHTML = arr[i][key]
}
tb.style.paddingLeft = "30px";
node.appendChild(tb)
}
}
Upvotes: 2
Reputation: 1170
if (key == 'unit_sell') {
tb.innerHTML = '£' + arr[i][key]
}
And a great tutorial for JS https://github.com/getify/You-Dont-Know-JS
Upvotes: 0
Reputation: 24549
This is an issue with comparison. You put:
if (key = 'unit_sell') {
When it should be:
if (key == 'unit_sell') {
The way you wrote it, you are using assignment instead of comparison.
Upvotes: 0