Using jQuery to change the background color of table cells to various shades

I am seeking assistance with a table I have created, and I want to implement a feature where the background color of cells with prices will change when clicked (using addClass(on)). The goal is to also change the background color of surrounding cells (using addClass(off)) while ensuring that cells with text and different colors remain unaffected.

In addition, I would like to retrieve the ID of the row to which the clicked cell belongs. Below is an example structure of a row:

<tr class="taksit" id="tek">
    <td><b>Tek Çekim</b></td>
    <td><?=$sontutar?> TL</td>
    <td><?=$sontutar?> TL</td>
    <td><?=$sontutar?> TL</td>
    <td><?=$sontutar?> TL</td>
    <td><?=$sontutar?> TL</td>
    <td><?=$sontutar?> TL</td>
    <td><?=$sontutar?> TL</td>
</tr>

I have attempted various methods suggested here but have not been successful in implementing this functionality. Any suggestions on how to achieve this desired outcome?

Answer №1


$(document).ready(function() {
    $('table#specificID tbody td').on('click', function() {
        $(this).closest('tbody').find('td').removeClass('active');
        $(this).addClass('active');
    });
});

Answer №2

$(".clickable-td").on('click',function(){
  // store the clicked element
  var selectedElement = $(this);

  // remove background color from other clickable elements 
  $(".clickable-td").css('background','none');

  // change the background color of the clicked <td>    
  selectedElement.css('background','blue');

  var rowIdentifier = selectedElement.closest('tr').attr('id');
});

Let me elaborate on my approach here.
Initially, to target specific <td> elements for click events and background modifications, it's practical to assign a common class like "clickable-td". Alternatively, you could designate an exclusion class such as "noClick" for your requirements.

For adjusting the <td> background color, numerous methods can be utilized. In this demonstration, the straightforward .css('background','blue'); was implemented, but in actuality, more intricate logic may be advisable.

The rowIdentifier is obtained by examining the nearest ancestor that is a <tr> with the assistance of the closest() function, followed by inspecting the id attribute.

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 property value for -webkit-overflow-scrolling: touch is not valid

Can someone help me figure out why this code isn't working? I included it in both my html and body elements, but I keep getting an error message saying "invalid property value" and it's crossed out. Initially, I tried using it within my media que ...

Implementing Cross-Origin Resource Sharing (CORS) authentication on Internet Explorer with

I have a myriad of inquiries that I could potentially pose, but let's kick things off with this one that has been persistently nagging at me. In my setup, I have a development environment within the intranet zone and a web service in the internet zon ...

Is there a way to display a Bootstrap popover for a button when another button is clicked?

Is there a way to manually display popovers instead of triggering them on element click events? Below is an example code snippet featuring two buttons: Click me: displaying popover upon clicking. (this should not occur) Show click me popover: intended ...

What is the best way to modify the underline style of a tab in Material UI?

I'm trying to customize the underline of: https://i.stack.imgur.com/J2R1z.png Currently, I am using material ui version 4.12.3 The code snippet for generating my tabs is below: function renderTabs(): JSX.Element { return ( <Tabs className={cla ...

Instruments for crafting an application compatible with a wide range of web browsers

Currently tackling various browser challenges. I find myself wondering whether it's achievable to create an application that is compatible with all browsers, or at least the majority. Should it be a web application? Any recommendations on frameworks a ...

Vue application experiences issues with styles not displaying as expected

I've recently put together my very first Vue web application. As I was building it, I ran into an issue with my delete buttons not displaying correctly. No matter what styling adjustments I made, the problem persisted. Any suggestions on how to fix th ...

The div extends beyond its parent due to its height

This issue is concerning. https://i.stack.imgur.com/on8t9.jpg The border of the div extends beyond the red line. I have set this for body and html: html { height: 100%; } ::-webkit-scrollbar { width: 0px; background: transparent; /* make scrol ...

Showing both labels and input fields side by side with CSS developments

I'm having trouble getting the label and input elements to display on the same line for this form. I've tried using CSS properties like display, float, and clear, but the result is not what I intended. Here is how the form should look: form & ...

What is the best way to showcase my divs in a masonry layout using flexbox?

I am attempting to design display divs in a masonry style using flex/flexbox. The layout must consist of a maximum of 2 columns, with each div having the same width (thus dividing into 2 columns equally) while varying in height based on their content. Some ...

What causes the source code of a website to change when accessed from various browsers?

When analyzing the source code of bartzmall.pk using various browsers, it reveals different classes being added to the html tag for each browser. For Firefox: <html class="firefox firefox53 otherClasses"> For Chrome: <html class="webkit chrome ...

Failure of AJAX HTML function to retrieve value from textarea

I am displaying data in the first three columns of a table, with the last column reserved for user feedback/comments. However, when the form is submitted, the values in the textarea are not being posted. The table has 6 rows. The Sample TR: <tr> &l ...

Passing an array to PHP using AJAX

I have been attempting to send a JavaScript array to a PHP file using AJAX. Here is the JS code: $('#basket').on('click',function(){ $.ajax({ type: "GET", url: "basket.php", data: {vektor: itemNameArray}, ...

Ways to eliminate a Collection of CSS2DObject from the environment

I have a dynamic msg_arr array of strings that I want to display visually, and I need to clear the existing errs Group of CSS2DObject from the scene before creating a new errors Group. The issue here is that although the new CSS2DObjects are added success ...

Learning how to update a database using AJAX, jQuery, PHP, and MySQL can greatly enhance your web development

I am facing an issue with updating a database using AJAX without reloading the page. Even though I receive a success message after making the AJAX call, the database is not getting updated as expected. Here is my code: JS: $('.start-time-class' ...

Why won't divs align vertically in the center?

I'm struggling to create a navigation bar layout where the icons are centered both horizontally and vertically within their cells. http://jsfiddle.net/digorydoo/j2v5m7gr/ I can't seem to pinpoint what's causing the issue with my current la ...

Having difficulty positioning menu items beside the logo

I am facing an issue with aligning my menu items next to the logo in my navbar. Currently, the menu items are positioned slightly below and to the right of the logo. Although the horizontal alignment is correct, I need to adjust the vertical positioning to ...

Using the :not() selector in complex JQuery statements

My goal is to select all of my < li >s that do not have the word 'Month' in their text. I am currently using a selector with a variable called current which holds the string 'Month'. $('section ul li:not(section ul li:contai ...

Include a character on the right side without shifting the text to the left

Below is the HTML code I am currently working with: <div class="last_img"> <p>Galutinė žetono išvaizda:</p> <span class="zetin11">A</span> <span class="zetin12">A</span> < ...

Align a span vertically within a div

I need help aligning the content "ABC Company" vertically within a div using Bootstrap 4's alignment helper classes. Despite my efforts, I have not been successful. Here is the code I am using: <div class="container" style="width: 740px;"> < ...

Creating a Form with Dynamic HTML when Button is Clicked

I have been working on enhancing the functionality of my website app located at , but unfortunately, I have not been successful so far. My goal is to introduce a vendor information form with just one click of a button and then enable users to add products ...