"Using jQuery to add emphasis to a table row and remove it again

I have a table with multiple rows, where I have styled each odd row in one shade of gray and the even rows in slightly different shades to make it easier to read.

When clicking on a row, I am currently highlighting it with a different color to indicate which record has been selected. However, I'm not sure how to revert the color back to its original when selecting a different row.

Currently, I find myself having to set all the rows back to their alternate gray colors as a workaround, and then apply the new highlighted color to the selected row.

I was hoping to find a better way to achieve this effect without resorting to such workarounds.

$(document).on("click","#div2 tr#abc", function(event) {

    barcode = $(this).data('barcode');

    $('tr:odd[id="abc"]').css('backgroundColor', '#FAFAFA');
    $('tr:even[id="abc"]').css('backgroundColor', '#F2F2F2');

    $(this).css('backgroundColor','#FFD6F5');

});

Answer №1

My recommendation is to utilize CSS classes instead of relying on the css() function:

CSS

.highlight { background-color:yellow }

jQuery

When a row is clicked, first remove the highlight class from all rows and then add this class to the clicked row:

$('#yourTable tr').on('click', function() {
   $('#yourTable tr').removeClass('highlight');
   $(this).addClass('highlight');
});

Answer №2

Avoid inline styling and utilize classes instead.

Update your CSS file with the following:

.selected {
    background-color: #FFD6F5
}

Update your JavaScript code as follows:

$(document).on("click","#div2 tr", function(event) {
    $('tr').removeClass('selected');
    $(this).addClass('selected');
});

Answer №3

Here is a simple solution for your problem:

By toggling CSS classes on rows, you can achieve the desired effect.

$(document).on("click","tr", function(event) {

  $('tr').removeClass('active');  
  $(this).addClass('active');

});
tr:nth-child(even) {background: #F2F2F2}
tr:nth-child(odd) {background: #FAFAFA}

td{ width:200px; height:20px;border:1px solid black;}

tr.active{background:#FFD6F5};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      </td>
    <td>
      </td>
    
    </tr>
  <tr>
    <td>
      </td>
    <td>
      </td>
    
    </tr>
  <tr>
    <td>
      </td>
    <td>
      </td>
    
    </tr>
  <tr>
    <td>
      </td>
    <td>
      </td>
    
    </tr>
  <tr>
    <td>
      </td>
    <td>
      </td>
    
    </tr>
  <tr>
    <td>
      </td>
    <td>
      </td>
    
    </tr>
    </table>

Answer №4

If you want to improve your code, consider working with classes instead of directly setting css attributes:

CSS (order matters; refer to Rory McCrossan's response for different baseline coloring):

.color-even { background-color: #F2F2F2; }
.color-odd  { background-color: #FAFAFA; }
.color-hilite { background-color: #FFD6F5; }

JavaScript:

$(document).ready( function() {
    //...
    $('tr:even').addClass('color-even');
    $('tr:odd').addClass('color-odd');
    //...
});

//...

$(document).on("click","#div2 tr", function(event) {
    barcode = $(this).data('barcode');

    $('.color-hilite').removeClass('color-hilite');
    $(this).addClass('color-hilite');
});

If you want to allow selection of multiple rows, make sure to move the 'removeClass' method to where you handle deselection.

jsFiddle (live demo)

NB (id attribute)

In your click handler selector, you used the id 'abc' with the tr element. This may not be logical unless you have multiple rows sharing the same id. It's better to use classes for this purpose and you can add multiple classes in a single class attribute. jQuery makes handling this easier even though it can get a little tricky without convenience code.

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

Are you experiencing problems with JSON formatting?

Currently, I am facing an issue with populating an HTML table using JSON data. The problem arises when I try to populate the table with the JSON data that was provided to me. After careful examination, I suspect that the issue might lie in the formatting o ...

Retrieving a targeted data point from a JSON object

I am working with a json data that contains various properties, but I am only interested in extracting the uniqueIDs. Is there a way to retrieve ONLY the uniqueID values and have them returned to me as a comma separated list, for example: 11111, 22222? (I ...

How to set up a Carousel as the background within a div using Bootstrap 5

I'm attempting to create a visually appealing layout by showcasing a Carousel component behind some text. The idea is to have scrolling and fading images with a prominent header overlaid on top of them. I want the carousel images to be contained withi ...

Font that has been downloaded is not showing up on the HTML document

I recently downloaded a new font and ensured the file location is correct, but for some reason it's not working: <style> @font-face { font-family:"myfont"; src: url('fonts/Helvetica85Heavy_22449.ttf'); } h1 { font-family: ...

The "Read more" feature is not functional on mobile devices

I am encountering issues with my Wordpress blog on mobile screens. The "read more" button is not functioning, and the screen size does not fit properly on mobile devices. Visit abood250.com for more information. CSS Styling: /* =Global ----------------- ...

jquery's each method is not functioning as intended and causing unexpected issues

I'm in the midst of developing a website, and one section requires users to input their details into a form. My goal is as follows: When a user clicks the submit button with any empty fields, I want a span element (initially set to display none in CS ...

Customize scaffolding.less for the body element

Recently, I've been putting together a webpage and decided to incorporate Bootstrap into the design. However, after adding Bootstrap, I noticed that it changed the background color of the body on my site. I have included a link to the fiddle below for ...

Stop users from being able to input line breaks by pasting

I am currently facing a challenge with my code. Within the code, I have included a textarea where users can input the title of an article, and I want this title to be restricted to only one line. To achieve this, I created a script that prevents users from ...

Troubleshooting issue: Click function not responding inside Bootstrap modal

Below is the JavaScript code for my click function $(".addPizza").on("click", function(event) { event.preventDefault(); console.log("hello") let userId = $("#userId").attr("data-id"); let pizzaRecipe = $('#pizza-recipe').val().trim(); ...

jQuery is an excellent tool for implementing drag and drop folder upload functionality, all without

I am creating a drag and drop file uploader with basic functionality. Here is the code: HTML: <div class="drop-box drop-area"> <form enctype="multipart/form-data" id="yourregularuploadformId"> <input type="file" name="files[]" ...

Implementing a soft transition to intl-tel-input plugin

This tel-input plugin was developed by Jack O'Connor. You can find the plugin here: https://github.com/Bluefieldscom/intl-tel-input I have observed that the flags take approximately one second to download, and I would like to enhance this process wi ...

Is there a way to access a PHP value within a self-invoked jQuery function?

I have a page that creates n links using a foreach loop: ...some html and php code <?php foreach ($tables as $table):?> ... some elements generated ... <td><a onclick="setPortalId(<?php echo $table['id']?>);$('#file ...

Error: AJAX requesting page not listed in manifest

When using a cached HTML page and JQuery, I've encountered difficulty accessing a page from the server that is not listed on the manifest. Every attempt I make to access a page not included in the manifest results in a return of null or an empty strin ...

Is there a way for me to determine if a user has engaged with a form?

I'm surprised by how difficult it was to find information on this topic through Google. Currently, my struggle lies in wanting my form fields to change color based on validity only after the user has interacted with the form. I don't want invali ...

Positioning a div at the bottom of a webpage without using absolute positioning in HTML

Check out the fiddle. I've included some CSS to position the tab on the right side. My goal was to have those tabs in the lower right corner of the container. If I use absolute positioning for the div, it messes up the tab content width. I tried ad ...

What causes certain divs to protrude when the parent div has overflow:hidden property enabled?

Issue: I am facing difficulty aligning all elements within one div without any overflow issues. Even with the parent div set to overflow:hidden, some child divs are protruding out of the container. How can I resolve this problem? Example: http://jsfiddle. ...

How to effectively send data via POST request in ASP.NET to ensure that images are properly displayed on the form

Case Study : An ASP.NET web application includes a page called ShowDesign.aspx The ASPX page is equipped with various controls. Within the page, there's a DIV element where images are dynamically loaded from the code behind. The structure of the DIV ...

What is the best way to combine two arrays of objects in AngularJS?

How can I merge the existing object array with another one in AngularJS to implement the "load more" feature? Specifically, I want to add the AJAX response to the existing data each time. Currently, I have a variable called $scope.actions that holds the ...

Where should you incorporate Jquery within a PHP-heavy webpage?

I'm struggling to get my script working correctly on a page I created. It's a paginate script that links to the "newsblocks" class. Where should I place the script for it to function properly? <?php /* Template Name: [Newspage] */ get_heade ...

An issue has been identified with the functionality of an Ajax request within a partial view that is loaded through another Ajax request specifically in

Here is the current scenario within my ASP.NET MVC application: The parent page consists of 3 tabs, and the following javascript code has been implemented to handle the click events for each tab: Each function triggers a controller action (specified in t ...