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.

4
  • if (key = 'unit_sell') single = is for assignment. To do an equality check use == or === Commented Nov 18, 2019 at 15:32
  • Change to key == 'unit_sell'. You need a double = for if comparison. Commented Nov 18, 2019 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 Commented Nov 18, 2019 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 Commented Nov 18, 2019 at 15:37

3 Answers 3

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)
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

Whoever downvoted, care to explain why this answer is insufficient?
I didn't down vote, but I'm guessing it was downvoted due to the tb.innerHTML = arr[i][key] line not being in an else block after your if statement.
Ah ok, that's fair. I didn't notice that.
0
   if (key == 'unit_sell') {
        tb.innerHTML = '£' + arr[i][key]
    }

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.