R00059159
R00059159

Reputation: 167

Javascript displaying a var in code

I want the value of some vars to be shown in the string.

 function test()
 {
 var first = document.getElementById('first').value; //value ==hello
 var second = document.getElementById("second").value; //value == bye
 var third = document.getElementById("third").value;   //value == crazy
 var forth = document.getElementById("forth").value;    // value == night


 var myString = " \
 <script> \
 var firstValue = "\" + first + \""; \
 var secondValue = "\" + second + \""; \
 var thirdValue = "\" +third + \""; \
 var forthValue = "\" +forth + \""; \
 <\/script> ";

I want the string to display:

 <script> 
 var firstValue = " hello "; 
 var secondValue = "  bye "; 
 var thirdValue = " crazy "; 
 var forthValue = " night "; 
 </script> ";

Upvotes: -2

Views: 106

Answers (4)

WestMountain
WestMountain

Reputation: 625

Just use the

`
var string = `<script> 
 var firstValue = " hello "; 
 var secondValue = "  bye "; 
 var thirdValue = " crazy "; 
 var forthValue = " night "; 
 </script> ";`

Upvotes: 0

Sirko
Sirko

Reputation: 74036

I think your problem just boils down to wrong escaping in the string, which you should recognise simply by code highlighting:

 var myString = " \
 <script> \
 var firstValue = \"" + first + "\"; \
 var secondValue = \"" + second + "\"; \
 var thirdValue = \"" +third + "\"; \
 var forthValue = \"" +forth + "\"; \
 <\/script> ";

You always escape the characters you want to keep in your string and not those, which have a syntactical meaning in the definition!

Upvotes: -1

Zword
Zword

Reputation: 6793

To convert any value to string just concatinate value with an empty string like - ""+document.getElementById('1').value

See this fiddle

Upvotes: -1

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60493

variables names in javascript can't start with a number.

So change your variable names.

var name1  = document.getElementById('1').value;

should be better.

Upvotes: 2

Related Questions