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()">
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>';
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.
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
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>';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.