Home > Back-end >  jQuery add class to specific ID based on MYSQL fetch
jQuery add class to specific ID based on MYSQL fetch

Time:06-08

I try to solve this problem:

  1. I have a from MYSQL fetched element in PHP:
<button  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.

  1. I added a Jquery script:
$(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!

CodePudding user response:

You could solve that by using a more general "class" selector like so:

PHP fetched HTML:

<button >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:

CodePudding user response:

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  id="idLike-1">Button text</button>
<button  id="idLike-2">Button text</button>
<button  id="idLike-3">Button text</button>

  • Related