0

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.

Clarity
  • 10,730
  • 2
  • 25
  • 35
user3580480
  • 442
  • 7
  • 14
  • 45
  • `if (key = 'unit_sell')` [single `=` is for *assignment*](https://stackoverflow.com/questions/11871616/in-javascript-vs/). To do an equality check use `==` or `===` – VLAZ Nov 18 '19 at 15:32
  • Change to `key == 'unit_sell'`. You need a double `=` for `if` comparison. – nurdyguy Nov 18 '19 at 15:32
  • 1
    Even after fixing the typo, you have `tb.innerHTML = ` after the if block which is going to overwrite everything. So it will overwrite the code you set in the if block – Patrick Evans Nov 18 '19 at 15:34
  • Thanks Patrick, I needed to add the second "tb.innerHTML =" into an ELSE on the FOR LOOP. Please add as an answer and I will accept – user3580480 Nov 18 '19 at 15:37

3 Answers3

2

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)
  }
}
Clarity
  • 10,730
  • 2
  • 25
  • 35
0

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.

Jeremy Harris
  • 24,318
  • 13
  • 79
  • 133
0
   if (key == 'unit_sell') {
        tb.innerHTML = '£' + arr[i][key]
    }

And a great tutorial for JS https://github.com/getify/You-Dont-Know-JS

Safi Nettah
  • 1,160
  • 9
  • 15