3

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!

2 Answers 2

2

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.

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

1 Comment

wow! :) jQuery <3 thanks a lot to both of you, going to read jquery documentation little deeper :)
1

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."'>";

2 Comments

It's quite possible that the div he needs to toggle isn't adjacent to the clickable div. (I know it is in the example, but the whole thing just breaks down when it isn't).
Yes of course, this could be handled with selector wildcards and appending and ID to the ID's when looping in PHP.

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.