1

I want to generate a certain number of divs using PHP with different ids, I know how to generate them for a set number, but how do I generate on click, with different ids? Also, if I wanted to delete a div (and its corresponding id) how would I do that?

This is the code I have for generating (6) divs

 $element = "<div></div>";
    $count = 6;
    foreach( range(1,$count) as $item){
        echo $element;
    }

I need something like the click() in jquery/javscript (but in PHP) to trigger div creation instead and I don't even know where to start.

2
  • 2
    PHP can't handle clicking. You probably want Javascript. Commented Aug 23, 2012 at 5:00
  • because it's server side, right? how would i do this in javascript then Commented Aug 23, 2012 at 5:05

3 Answers 3

4

In JavaScript you can do

function createDiv(id, parent)
{
    var elem = document.createElement('div');
    elem.id = id;
    document.getElementById(parent).appendChild(elem);
}

createDiv(10, id-of-parent-elem-to-append-to);

where 10 will be the ID of the new element and you will have to supply the ID of the element to which the new DIV should be appended, as the 2nd argument

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

2 Comments

In order to actually add it to your page... document.body.appendChild(elem);
@FilmJ yea, accidentally got submitted before I finished typing :)
1
echo "<div id='$item'></div>";

instead?

1 Comment

thanks for that answer, it answers my original question, but the javascript is the answer to my question in the comments. Thanks though.
1

Ok, to create them with different ids you can do something like this:

$element = "<div id=";
$count = 6;
foreach($id=0;$id<$count;$id++) {
    echo $element."div".$id."></div>";
}

In the same way as you appended the id you can append an onClick event that says something like this:

onclick="this.style='visibility:hidden;'";

or something along those lines. Hope this helps.

1 Comment

thanks for that answer, it's the actual answer to my original question, but the javascript is the answer to my question in the comments. Thanks though.

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.