views:

77

answers:

6

i am trying to use variable inside body. just see below sample code

<body>
 <div class="demo">
     <script>
     var count = 4;
      for(i=1;i<=count;i++){
          var varSlid = "A"+i;
          $('.demo').append('<div id= varSlid ></div></br>');
      }
     </script>
</div>
</body>

but it is throwing errors. please check and tell me where the error is?

A: 

Try this...

$('.demo').append($('div').attr('id', varSlid)).append('<br/>');

Also wrap this entire function in on dom ready like

$(function(){
    //your code here...
});
Teja Kantamneni
+3  A: 

Try This

var varSlid = "A"+i;
          $('.demo').append('<div id= ' + varSlid  + '></div></br>');
Amit
A: 

change: $('.demo').append('<div id= varSlid ></div></br>'); to: $('.demo').append('<div id=' + varSlid + ' ></div></br>');

Digital Human
+2  A: 

The error is that .demo hasn't finished parsing yet, so you shouldn't be attempting to manipulate it. This can cause serious issues in older versions of IE ("operation aborted", anyone?). Move the script to just outside the <div> tag:

<body>
<div class="demo">
</div>
<script>
     var count = 4;
      for(var i=1;i<=count;i++){
          var varSlid = "A"+i;
          $('.demo').append('<div id='+varSlid+'></div><br/>');
      }
</script>
</body>

As others have pointed out, you also need the quotation marks to work the variable into your HTML string, although this wouldn't have caused any errors - you would just end up with a bunch of elements all with the same id ("varSlid").

Andy E
A: 

It's : $('.demo').append('<div id="' + varSlid + '"></div></br>');

Squ36
A: 

Maybe it's my lack of jQuery-fu... but shouldn't </br> be <br/>?

Also, you shouldn't create 4 elements <div id= varSlid > since the id attribute should be unique.

Edit: You probably intended to use the value of the variable varSlid as the id attribute, but rit now it's part of a hardcoded string literal. You'd want to something more like:

$('.demo').append('<div id="'+varSlid+"'></div><br/>');
LeguRi
the varSlid is supposed to assign a new value in every loop. The problem is its been used as a regular string not as a variable
Teja Kantamneni
Thanks, I missed that! this is what I get when I answer SO questions before drinking some coffee in the morning ;)
LeguRi
thanks all. its working fine.. I will implement your valuable suggestions
poineer
@user399426 - ... if it's working fine then you should perhaps accept an answer? If you usd a solution not present in the answers, you can write your own answer and accept it!
LeguRi