tags:

views:

49

answers:

3

How to generate id for dinamic div tag using php or jquery?

example: php generates 36 divs, how to set each div unical id from 1-36?

+1  A: 

How about:

for($i = 1; $i < 37; $i++)
{
   echo "<div id='div-$i'></div>";
}

Edit: 2D version, even though you have one, I didn't realise this is what you wanted.

for($x = 1; $x <= 36; $x++)
{
    for($y = 1; $y <= 36; $y++)
    {
        echo "<div id='div-$x-$y'></div>";
    }
}
Wolfy87
Please note though, a valid html id must start with a character A-Z, a-z.
Chris
@Chris, that's why I used `div` as a prefix :)
Jacob Relkin
Its not working, because each dynamic div gets the same property- 1
Nation
Tnx, this solution worked for me :) <?php for($i = 0, $z = 10; $i < $z; $i++) { ?>
Nation
Oh, sorry, did you want it to be two dimentional like, 1-1, 1-2, 2-1, 2-2?
Wolfy87
Yes :) How to set break when $z=10? After 10, its start loop agen
Nation
Well I just edited, change 36 to what you want, it will make essentially a grid to the x and y you specify
Wolfy87
Anyway its repets from 36. I think its because i have php script for dynamic grid: <?phpfor ($k = 2; $k >= -3; $k--){ for ($j = -3; $j <= 2; $j++) { $st_x = ($k + 3) * 58 + ($j + 3) * 58; $st_y = (3 - $k) * 25 + ($j + 3) * 25; ?>
Nation
I use this code for position top and left
Nation
when i run your code without my, its working fine.
Nation
+1  A: 

Try this:

You can use PHP:

<?php for($i = 0; $i <= 36; $i++) { ?>
      <div id="div<?php echo $i; ?>"></div>
<?php } ?>

or JavaScript:

for(var i = 1; i <= 36; i++) {
    var div = document.createElement('div');
    div.id = 'div' + i;
    document.body.appendChild(div);
}
Jacob Relkin
Okey this solution worked for me :) <?php for($i = 0, $z = 10; $i < $z; $i++) { ?>
Nation
@Nation Then mark it as the solution: click the grey tick on the left hand side.
fredley
How to set brake? After 36, its start loop agen.
Nation
I mean break :D
Nation
@Nation, what do you mean?
Jacob Relkin
Do you know PHP break manual? How to set break when $z=10? After 10, its start loop agen from 1-10 and again, and again... How to stop it?
Nation
A: 
for(i=1;i<=36;i++){
  echo "<div id='my-div-$i'>".$divContents[$i]."</div>";
}
fredley
Tnx, this solution worked for me :) <?php for($i = 0, $z = 10; $i < $z; $i++) { ?>
Nation