Reputation: 13
I have the following as the code but i when i debug it from the chrome. I have seen that the id names are all +someInput +demo things like that. My aim is to pass the javascript variables to the ids. How can i do that? Thanks in advance.
for(i=0;i<5;i++){
var demo5 = "demo5"+i;
var someInput ="someInput" +i;
var demo = "demo"+i;
var demo1 = "demo1"+i;
var demo2 = "demo2"+i;
var demo3 = "demo3"+i;
var demo4 = "demo4"+i;
document.write('<tr>');
document.write('<td><p id=""+demo5 ></p></td>');
document.write('<td><p id=""+someInput onclick="myFunction(),myFunction5()"></p> </td>');
document.write('<td><p id=""+demo onclick="myFunction1(),myFunction5()"></p></td>');
document.write('<td><p id=""+demo1 onclick="myFunction2(),myFunction5()"></p></td>');
document.write('<td><p id=""+demo2 onclick="myFunction3(),myFunction5()"></p></td>');
document.write('<td><p id=""+demo3 onclick="myFunction4(),myFunction5()"></p></td>');
document.write('<td><p id=""+demo4 </p></td>');
document.write('</tr>');}
Upvotes: 0
Views: 826
Reputation: 407
in your example variable treat as string thats whats it's interpret same. see below i have concaternate the variable enclose with ''
for(i=0;i<5;i++){
var demo5 = "demo5"+i;
var someInput ="someInput" +i;
var demo = "demo"+i;
var demo1 = "demo1"+i;
var demo2 = "demo2"+i;
var demo3 = "demo3"+i;
var demo4 = "demo4"+i;
document.write('<tr>');
document.write('<td><p id=""+demo5 ></p></td>');
document.write('<td><p id=""+someInput onclick="myFunction(),myFunction5()"></p> </td>');
document.write('<td><p id="'+demo+'" onclick="myFunction1(),myFunction5()"></p></td>');
document.write('<td><p id="'+demo1+'" onclick="myFunction2(),myFunction5()"></p></td>');
document.write('<td><p id="'+demo2+'" onclick="myFunction3(),myFunction5()"></p></td>');
document.write('<td><p id="'+demo3+'" onclick="myFunction4(),myFunction5()"></p></td>');
document.write('<td><p id="'+demo4+'"> </p></td>');
document.write('</tr>');}
Upvotes: 0
Reputation: 2345
You need to concatenate the strings like
document.write('<td><p id="' + demo5 + '" ></p></td>');
in order to get your desired result. In your post, JS will interpret '... id=""+demo'
as a string, not escaped and not using the variable value.
EDIT: per comments added the '+'
Upvotes: 4