errata
errata

Reputation: 6031

Combining jQuery with PHP

I have some simple jQuery toggle script like this:

<script type="text/javascript">
$(document).ready(function() {
  $('#clickedit').click(function() {
    $('#st').toggle();
  });
});
</script>

And, of course, in my HTML I have some

<div id="clickedit">CLICK ITEM TO TOGGLE</div>
<div id="st">content to show/hide</div>

Now... If I am working with PHP and I am iterating through few 'items' and each 'item' has his content to show/hide I cannot set static ids to my divs because script just won't work. I can assign some item's id to my divs (something like echo "<div id='clickedit".$id."'>"; and echo "<div id='st".$id."'>";) but I don't know how to handle them in my jQuery script! I am just discovering jQuery and it is brilliant, but still confusing to me :) So any help would be great!
Thanks in advance!

Upvotes: 3

Views: 559

Answers (2)

Dustin Laine
Dustin Laine

Reputation: 38503

Use a class selector, and some jQuery sweetness!

<script type="text/javascript">
$(document).ready(function() {
  $('.div1').click(function() {
    $(this).next('.div2').toggle();
  });
});
</script>

Then your PHP would change to, you could remove your ID's:

echo "<div class='div1' id='clickedit".$id."'>"; and echo "<div class='div2' id='st".$id."'>";

Upvotes: 1

pilsetnieks
pilsetnieks

Reputation: 10420

I don't know your particular case but something like this should do the trick:

<div class="clickedit" id="clickedit123">CLICK ITEM TO TOGGLE</div>
<div class="st" id="st123">content to show/hide</div>

you set the class name to be able to assign the click events to all of them at once, but use the ID to have a specific ID for each item.

$('.clickedit').click(function() {
    var id = this.id.replace('clickedit', '');
    $('#st' + id).toggle();
}

And on the click event take the ID, take the generic part off the ID and use the ID to find the necessary element to toggle.

Upvotes: 2

Related Questions