Reputation: 1852
I want to use jQuery to open and close a div. But because the code that I use is dynamic and will be repeated 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 try to use this jQuery, but I guess 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 need to edit this correctly?
Upvotes: 2
Views: 873
Reputation: 3231
you can hook up all id's that start with review-
to respond
$('[id^="review-"]').click(function() {
$( '.categoryratings-' + $(this).attr('id') ).slideToggle('fast') ;
$( this ).toggleClass('active');
});
Upvotes: 0
Reputation: 8171
It'd be easier if you'd grouped your elements like below. By doing so, you don't need ID
s 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>
Upvotes: 2
Reputation: 4572
You can do it 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.
Upvotes: 3