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>`;

0

1 Answer 1

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());

Sign up to request clarification or add additional context in comments.

3 Comments

Your link is in Polish. Should probably change it to an English one since we are on an English website.
@chevybow Done, i accidentally copied before language change.
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

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.