0

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>');}
1
  • 1
    document.write writes to the document everything passed in the argument, literally. Commented Sep 4, 2014 at 9:06

2 Answers 2

4

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 '+'

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

1 Comment

I think you are missing + after demo5.
0

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>');}

Comments

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.