Jquery open div with dynamic id

I want to use jQuery to open and close a div. But since the code I'm using is dynamic and will repeat below each other, I need to use a dynamic id.

HTML:

<div class="categoryratings-review-<?php echo $this->htmlEscape($_review->getId())?>" style="display: none;">
   <p>Text</p>
</div>

<span class="showcategoryratings" id="review-<?php echo $this->htmlEscape($_review->getId())?>">
   <span class="showcategoryratings-text">Per category</span>
</span>

      

I am trying to use this jQuery, but I think the php line is not working:

$(document).ready(function() {
    $('#review-<?php echo $this->htmlEscape($_review->getId())?>').click(function() {
            $('.categoryratings-review-<?php echo $this->htmlEscape($_review->getId())?>').slideToggle("fast");
            $(this).toggleClass('active');
    });
});

      

How do I change this correctly?

+3


source to share


3 answers


You can do this without PHP in your Javascript.

$(document).ready(function() {
    $('.showcategoryratings').click(function() {
        var categoryId = $(this).attr('id').split('-')[1];

        $('.categoryratings-review-'+categoryId).slideToggle("fast");
        $(this).toggleClass('active');
    });
});

      



I think it works.

+3


source


It would be easier if you group your items as shown below. In doing so, you don't need to ID

at all. Take a look.



$(document).ready(function() {
    $('.showcategoryratings').on("click", function() {
        $(this).closest(".group").find(".categoryratings-review").slideToggle("fast");
        $(this).toggleClass('active');
    });
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="group">
    <div class="categoryratings-review" style="display: none;">
        <p>Text1</p>
    </div>
    
    <span class="showcategoryratings">
        <span class="showcategoryratings-text">Per category1</span>
    </span>
</div>

<div class="group">
    <div class="categoryratings-review" style="display: none;">
        <p>Text2</p>
    </div>
    
    <span class="showcategoryratings">
        <span class="showcategoryratings-text">Per category2</span>
    </span>
</div>

<div class="group">
    <div class="categoryratings-review" style="display: none;">
        <p>Text3</p>
    </div>
    
    <span class="showcategoryratings">
        <span class="showcategoryratings-text">Per category3</span>
    </span>
</div>
      

Run codeHide result


+1


source


you can connect all id starting with review-

to answer

 $('[id^="review-"]').click(function() {

    $( '.categoryratings-' + $(this).attr('id') ).slideToggle('fast') ;

    $( this ).toggleClass('active');

 });

      

0


source







All Articles