2

I'm trying to print the value of a variable in the first column of my table, but when I run the method, I get the name of the variable instead

I have the following code

function writeTable() {
  var table;
  var uInput = document.test.input.value;
  table = "<table><tr><th colspan=3>Table Header</th></tr>";
  table += "<tr><th>Column1</th><th>column2</th><th>column3</th></tr>";
  table += '<tr><td>uInput</td><td>Value2</td><td>value3</td></tr>';
  document.write(table);
}
<form name="test">
  <input type="text" name="input">
</form>
<input type="submit" name="submit" value="Write Table" onclick="writeTable()">

2
  • 5
    String concatenation. Commented Aug 15, 2017 at 17:14
  • Also avoid the legacy DOM notation, document.test.input.value;. Modernize with something like var uInput = document.querySelector('input[name="input"]'); Commented Aug 15, 2017 at 17:17

4 Answers 4

5

You need to change this line:

table += '<tr><td>uInput</td><td>Value2</td><td>value3</td></tr>';

To use template literal:

table += `<tr><td>${uInput}</td><td>Value2</td><td>value3</td></tr>`;

Or standard concatenation

table += '<tr><td>' + uInput + '</td><td>Value2</td><td>value3</td></tr>';
Sign up to request clarification or add additional context in comments.

1 Comment

Standard concat, that's what I was looking for. Thanks!
0

You need to concatenate the string:

table+= '<tr><td>'+uInput+'</td><td>Value2</td><td>value3</td></tr>';

Remember that everything between single or double quotes is interpreted as a string. However your uInput is a variable. To make sure JavaScript get's the variable you need to concatenate. That means pasting the string parts and the variable together using the +. Purgatory's answer has a nice ecmascript 6 solution too.

Comments

0

In print statement, you have to concatenate variable with "+" sign.
Your function 2nd last row looks like:

table+= '<tr><td>'+ uInput + '</td><td>Value2</td><td>value3</td></tr>';

1 Comment

Yes, four other people already stated this. What does your answer add that theirs doesn't?
0

use

table+= '<tr><td>' + uInput + '</td><td>Value2</td><td>value3</td></tr>';

to concatenate your string.As well as for the standards ,use

uInput = document.getElementsByName('input').value 

in your javascript

4 Comments

There is no getElementByName
You made my point. It's getElementsByName, not getElementByName
And using getElementsByName() would return a collection so you would also have to iterate through them which you don't explain or give an example of making your answer not very useful / incomplete.

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.