Reputation: 21
I try to solve this problem:
<button class="like-btn" id="idLike-'.$row['id'].'">Button text</button>
Currently, there are 3 fetched elements and every fetched element has its own id automatically e.g. idLike-1, idLike-2, idLike-3 etc.
$(document).ready(function(){
$("#idLike-2").click(function(){
$("#idLike-2").addClass("btn-first");
});
});
This works fine with the idLike-2 element of course, but I cannot find an ultimate solution for this script to work every id separately e.g. if I click on the idLike-1, only this element has a new class.
Thank you for your help!
Update:
If I try to save the current state of the element into the localStorage, the state of all elements will be saved. My full code:
$(document).ready(function(){
$(document).ready(function() {
if(localStorage.getItem('isCliked')){
$(".like-btn").addClass('liked-btn');
$(".like-btn").removeClass('like-btn');
}
$('.like-btn').on('click',function() {
$(this).addClass('liked-btn');
$(this).removeClass('like-btn');
// set the value upon clicking
localStorage.setItem('isCliked', true)
});
});```
Upvotes: 0
Views: 61
Reputation: 22323
1 alternative option is using wildcard on id.
$('button[id*="idLike-"]').click(function() {
$('button').removeClass("btn-first");
$(this).addClass("btn-first");
});
.btn-first {
background: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="like-btn" id="idLike-1">Button text</button>
<button class="like-btn" id="idLike-2">Button text</button>
<button class="like-btn" id="idLike-3">Button text</button>
Upvotes: 0
Reputation: 164
You could solve that by using a more general "class" selector like so:
PHP fetched HTML:
<button class="like-btn">Button text</button>
Javascript:
$(document).ready(function() {
$(".like-btn").click(function() {
$(this).addClass("btn-first");
});
});
You can target the jQuery element triggering the event using the $(this)
selector.
References:
Upvotes: 2