Home > Blockchain >  using toggleclass on a specific item using id
using toggleclass on a specific item using id

Time:09-27

I am trying to add a button to my site for every item that I have. So basically, I have a list of items and each one of them has a button next to them so that the user can select the wanted item. The problem I am facing is that I can change all of the button's classes when I press one of the buttons but I don't know how to do this depending on the id of the item, this is my toggleclass code so far, when I press a button all buttons become green instead of just one.

$(".btn-add").toggleClass("btn-default").toggleClass("btn-success")

This is my html code for the button

<a class="btn btn-default btn-add" onclick='select_item({{item.id}})'>
    <i class="fa fa-fw fa-square-o"></i>
</a>

Thank you for your time and for your help.

CodePudding user response:

What happens when you are clicking a button with toggleClass is that all the other buttons that have that class name will be updated.

A solution that you can do if you still want to use the toggleClass function of jquery is to make a unique class name for each button. You can utilize using an index or other variables that may be related to a certain item in your list.

const buttonAdd = `.btn-add-${index}`;
$(buttonAdd).toggleClass("btn-default").toggleClass("btn-success");

this way, every button will have a unique class name.

or, it might be better to use id for the selector of the button (if you are using the .btn-add for some css and stuff)

const buttonAdd = `#btn-add-${index or id}`;

then the the button itself should have a functionality of adding an id dynamically:

<a id="{dynamic value here}" class="btn-add ...">... </a>
  • Related