Within a loop featuring multiple buttons, apply a class toggle specifically to the button that is clicked on

CSS:

.btn-category-list-col {
    background:#f4f6f9;
    border: 0 !important;
}
.btn-category-list-col:hover {
    background: #E2EEFC;
}
.btn-category-list-col button:hover {
    font-weight: bold;
}

.btn-category-list-col-click {
    background: #E2EEFC;
}

.btn-category-list-col-click button {
    font-weight: bold;
}

Looped button:

<td class="p-0 btn-category-list-col">
    <button type="button" value="${cat.category_id}" class="category_sort btn float-left" data-toggle="modal" data-target="#createCategory">${cat.category_name}</button>
</td>

Script

        $(document).on('click', '.category_sort', function (e) {
        e.preventDefault();
            $(".btn-category-list-col").toggleClass("btn-category-list-col-click");
        });

https://i.sstatic.net/8yR2w.png

My question is about the onclick function in my script. When I click on a button, it changes the classes of all buttons instead of just the one clicked. How can I modify it to only affect the specific button that was clicked?

Answer №1

To target a specific button in jQuery, you can utilize the attribute selector instead of just selecting by class.

If we assume that cat.category_id is unique,

<!-- Add a data-id attribute to the button -->
<td class="p-0 btn-category-list-col">
    <button type="button" value="${cat.category_id}" data-id="${cat.category_id}" class="category_sort btn float-left" data-toggle="modal" data-target="#createCategory">${cat.category_name}</button>
</td>
 $(document).on('click', '.category_sort', function (e) {
   e.preventDefault();
   let id = event.target.dataset.id;
   if (id) {
     $(`button[data-id=${id}]`).toggleClass("btn-category-list-col-click");
   }
 });

Answer №2

It's a bit perplexing why you're seeking a JavaScript answer when your question includes jQuery code. Nevertheless, I'll provide you with the solution:

document
  .querySelectorAll('.category_sort')
  .forEach(button =>
  {
    button.onclick = event =>
    {
      event.preventDefault();
      button.closest('.btn-category-list-col').classList.toggle('btn-category-list-col-click');
    }  
  })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The directive I created is being disrupted by the Angular require directive

Recently, I created a custom directive inspired by a solution on Stack Overflow that restricts user input to only digits: .directive('onlydigitinput', function () { return { require: 'ngModel', link: function ( ...

What steps should I take to address the issue with my navbar?

I've written some code that creates a hamburger icon on mobile devices. When the user clicks it, a wave effect covers the screen, but I'm facing an issue where the wave doesn't cover the input field. My query is: how can I make the input fi ...

PHP conditionals

Viewing the webpage www.evolvedtools.org/Genr8PageIntro.php, I have implemented a method to fetch blogs from my wordpress.org blog and display them on this particular page using some simple php markup: In the header of the page: <?php require('. ...

I'm having issues with jQuery not functioning properly on my HTML page. The expected alert is not popping up upon page load

For some strange reason, I was expecting the alert "Doc Ready" to pop up, but it's not happening. What could be going wrong? The jQuery library is located in the js directory and I've tested it on all browsers but it's still not working. I a ...

Obtain a nested array of objects from Mongoose's Model.find() method and then make modifications to the inner array

I need to retrieve an array of objects with a specific ID from my database within a server route, and then update a property of an object within that array (rather than returning just the objectID, I want to return the Document as an object with the specif ...

Eliminate unnecessary spacing from the sticky container

Trying to implement a sticky menu in an angular 14 project using angular material 14 has been quite challenging for me. Initially, I attempted to use the 'fixed' position, but encountered issues where the menu would consistently return to the to ...

Maintaining Aspect Ratio and Adding Letterboxes with Next.js Image

In my Next.js app, there is a section dedicated to displaying selected photos from a gallery. It's crucial for this area to maintain a fixed size of 566px*425px as users navigate through images or when a photo is loading. While the layout is responsiv ...

JavaScript - filter out values not included in specified list of attributes

I am seeking a technique that, when provided with a list of attributes, retains only the values associated with keys present in the list. For instance: attrs = ['a', 'b', 'c'] obj = {'a': 1, 'b': 2, &apos ...

The nested division remains confined within its parent container without extending into other sibling elements

My table layout is quite complex, and I need to implement a hover menu that appears with its position adjusted based on each row's position. Each row in the table is generated dynamically using React props.map function, which gives me the flexibility ...

Execute two queries using MongoDB and Node.js

I'm currently facing a minor issue that I can't seem to resolve. My challenge is to pass two queries to my add_people.ejs file. While I can successfully pass one query, I am unsure of how to pass the second one. Here is an example of what I have ...

What is the best way to establish a connection with MSSQL using Node.js within a Vue.js frontend environment

Seeking assistance with connecting Vue.js app to remote MSSQL server. Incorporating node.js and utilizing the mssql library, encountering errors post-setup. How can I configure settings for successful mssql connection? What are effective solutions for r ...

AngularJS helps to organize data and manipulate information within a single page,

In need of assistance with a code that retrieves employees from a controller and applies pagination while filtering records. The issue arises when attempting to filter from a page other than the first, as it does not display any filtered results. The code ...

Struggling with grasping the concept of Filtering Array in Eloquent Javascript Chapter 5?

Currently diving into the world of JavaScript through the enlightening pages of Eloquent JavaScript. Chapter 5 has been a breeze so far, except for one line of code inside a console.log statement that has me stumped: function filter(array, test) { ...

What is the best method for calculating the total of a mongoose attribute?

I am attempting to calculate the sum of schema using reduce. However, the current code is not adding the items together but rather placing them next to each other. For example, 20 + 30 should result in 50, but instead it gives me 02030. Is there an issue w ...

Scaling Three.js Mesh to fit renderer while maintaining aspect ratio

Currently, I am using the STLLoader plugin from the Github repository of three.js. This is a snippet of my code: this.loadSTL = function(scene, stlFile){ var loader = new THREE.STLLoader(); loader.addEventListener('load', function(g ...

Stop clicks from interfering with dragging in three.js

My GLTF model in Three.js has objects within it, and I want the camera to zoom in on an object when the user clicks on it. However, I am facing an issue where if the user drags after clicking on an object, a click is triggered upon releasing the mouse butt ...

How can I ensure that Chakra UI MenuList items are always visible on the screen?

Currently, I am utilizing Chakra UI to design a menu and here is what I have so far: <Menu> <MenuButton>hover over this</MenuButton> <MenuList> <Flex>To show/hide this</Flex> </MenuList> </ ...

Having difficulty positioning text within a div with a fixed height

I'm facing a challenge in aligning text at the center of a div. My goal is to horizontally center it, but position it slightly higher than the vertical center. The div has a fixed height of 45%. How can I achieve this layout? .galf { width : 100%; he ...

Having issues with the integration of Sweet Alert and $_session variables

I am having trouble getting a sweet alert to show when the SQL condition is true. Below is the code for the back-end implementation. <?php include "../../../config/config.php"; if (isset($_POST['submit-slider'])) { $title = $_POST[&apos ...

Is there a streamlined approach to signal a successful callback to $q.all without the need to define a $q.defer() variable?

Within my application, I have a mixture of synchronous and asynchronous methods. Here is an example of code from one of the controllers: $q.all([ asyncMethod1(), syncMethod1() ]) .then(function (results) { Even though I don't actually need t ...