0

I'm trying to format a table of data as a string and return it to the page. I have the following, but I'm afraid this isn't a valid way to define my variable.

var tableOutput = ' <
  table class = \"child-info\" cellpadding=\"5\" cellspacing=\"0\" border=\"0\" style=\"padding-left:50px;\">'+
'<tr>' +
'<td>Level:</td>' +
'<td>' + d.deg_codes[0] + '</td>' +
  '</tr>' +
  '<tr>' +
  '<td>Level:</td>' +
  '<td>' + d.deg_codes[1] + '</td>' +
  '</tr>' +
  '</table>';
return tableOutput;

However, it works when I just return the entire definition statement by itself. Unfortunately, I need it as a variable to be able to modify it. Is there a better way to define this? Or do I have to do a huge number of appends?

EDIT:

Got it working as:

      var tableOutput = `
      <table class = "child-info" cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">
          <tr>
              <td>Level USF Tampa:</td>
              <td>${d.deg_codes[0]}</td>
          </tr>
          <tr>
              <td>Level USF Tampa:</td>
              <td>${d.deg_codes[1]}</td>
          </tr>
      </table>`;
rborum
  • 124
  • 1
  • 11

1 Answers1

1

Use javascript template strings

`string text line 1
 string text line 2`

Also remove unnecessary quotes ' and + for concatenation

function showTable() {
  const d = {
    deg_codes: [3434, 4444]
  };

  var tableOutput = `<table class = "child-info" cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">
          <tr>
              <td>Level:</td>
              <td>${d.deg_codes[0]}</td>
          </tr>
          <tr>
              <td>Level:</td>
              <td>${d.deg_codes[0]}</td>
          </tr>
      </table>`;

  return tableOutput;
}

document.write(showTable());
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
vicbyte
  • 3,690
  • 1
  • 11
  • 20
  • Your link is in Polish. Should probably change it to an English one since we are on an English website. – chevybow Sep 12 '18 at 16:09
  • @chevybow Done, i accidentally copied before language change. – vicbyte Sep 12 '18 at 16:10
  • You can take out the language string in the URL and MDN will try to pick a language-appropriate version. I always paste MDN urls as, for example, `https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals` – Stephen P Sep 28 '18 at 00:52