Highlighting a row upon being clicked

How can I implement a feature in my HTML page that highlights a row when selected by changing the row color to #DFDFDF?

If another row is selected, I would like the previously selected row to return to its original color and the newly selected row to be highlighted.

Note that I want the top header to be exempt from this color changing behavior.

You can view the fiddle here: http://jsfiddle.net/q42L2/

Thank you in advance for your assistance.

<div id="results" class="scrollingdatagrid">

  <table id="mstrTable" cellspacing="0">
     <thead>
      <tr> 
        <th>File Number</th>
        <th>Date1</th>
        <th>Date2</th>
        <th>Status</th>
        <th>Num.</th>
      </tr>
    </thead>
    <tbody>
      <tr> 
        <td>KABC</td>
        <td>09/12/2002</td>
        <td>09/12/2002</td>
        <td>Submitted</td>
        <td>0</td>

      </tr>
      ... more table rows ...
    </tbody>
  </table>

</div>

Answer №1

Here is a potential starting point (not tested). This code will guide you in the right direction. After creating the table, include this code either by deferring it or by calling initSelectableTable from the onload function. Remember to set the id of your table to "SelectableTable".

var OldColor = "";
var SelectedRow = null;
var SelectedColor = "#DFDFDF";

initSelectableTable("SelectableTable");

function onCellClicked(cell) {
    if (cell.parentNode) {
        if (SelectedRow) SelectedRow.style.backgroundColor = OldColor;
        SelectedRow = cell.parentNode;
        OldColor = SelectedRow.style.backgroundColor;
        SelectedRow.style.backgroundColor = SelectedColor;     
    }
}

function initSelectableTable(tableId) {
    var elTable = document.getElementById(tableId);
    if (elTable) {
        var cells = elTable.getElementsByTagName("td");
        for (var i = 0; i < cells.length; i++) {
            cells[i].onclick = function () { onCellClicked(this); }
        }
    }
}

I hope this information proves useful...

Answer №2

$('tbody tr').on('click', function (event){
  $('tbody tr').css('background-color', 'white');
    $(this).css('background-color', 'blue');
  });

http://jsfiddle.net/username1234/ABC123/4/

Give this solution a try, it has been tested and works perfectly

Answer №3

To implement this functionality using jQuery, you can use the code snippet below:

$(document).ready(function () {       
  $('#mstrTable tr').not('thead tr').click(function () {
    $('#mstrTable tr').css('background-color', 'white');
    $(this).css('background-color', '#DFDFDF');             
  }); 
});

Check out the DEMO here

Note:

We have excluded the thead elements from the selection using the not method.

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

Tips for utilizing a for loop within an array extracted from a jQuery element for automation

I am looking to streamline the process using a for loop for an array containing 10 image files in the parameters of initialPreview and initialPreviewConfig. My envisioned solution involves the following code snippet: for (i = 0; i < 11; i++) { "< ...

Guide to customizing color themes using Twitter Bootstrap 3

Recently, I dove into the world of Twitter Bootstrap 3 without any prior experience with earlier versions. It's been a learning curve, but I managed to set up a WordPress theme using it as the framework. All my elements are in place, but they all see ...

Is there a way to successfully submit a form in PHP once it has been validated using JavaScript?

I'm interested in creating a register/login system. I've set up a form in Register.php and handled the validation part in JavaScript, but I'm encountering an issue where no values are being sent to the database upon clicking submit. Registe ...

Maintain the fancybox open even in case of ajax errors

I'm having an issue with my code where the fancybox closes automatically after displaying the error message briefly. I want it to remain open so that users have more time to fix their errors. What could be causing this problem? $(document).ready(func ...

Retrieving metadata using breeze is taking too long

Using breeze in my MVC 4 application to fetch data from a remote SQL Server database with about 40 entities. Surprisingly, the loading of metadata is taking longer than expected, ranging between 14s and 35s even though the size is just around 600kb. Howev ...

What is the option for receiving automatic suggestions while formatting components in a react.js file?

When styling elements in our app using app.css or styles.css, VS Code provides auto-suggestions. For example, if we type just "back" for background color, it will suggest completions. However, this feature does not work in react.js or index.js. Why is that ...

There is no need for updates as git is already current for some mysterious reason

As a newcomer to git, I've been trying to wrap my head around it but still struggling. Can someone help clarify this for me? My question pertains to the 'master' branch in git which contains the following code: const list = [ 'h&ap ...

React Native does not support Laravel Echo's listenForWhisper functionality

I have successfully implemented private channels and messaging in my Laravel App using websockets:serve. Now, I am attempting to enable whisper functionality for the typing status but encountering some issues. When sending a whisper: Echo.private('c ...

What could be causing the load() function in my AJAX to not work properly in this code?

I am trying to implement a script that loads a navigation menu (ul element) from one HTML page to a specific div on another page. The ul element has a unique id, and I am using this id to load only the ul element and not the entire HTML page it is a part ...

Obtain a variety of selections for multiple selects and individually incorporate them into a standard select menu

Is there a way to select multiple options from a list and add them to another list without losing any selections? Currently, when I add two selected options, they combine into one in the target list. Check out this JSFIDDLE EXAMPLE for reference. Here is ...

The Javascript executor in Selenium is delivering a null value

My JavaScript code is causing some issues when executed with Selenium's JavascriptExecutor. Strangely, the code returns null through Selenium but a value in Firefox developer console. function temp(){ var attribute = jQuery(jQuery("[name='q& ...

Displaying an array of data using ng-repeat, only showing records where the value is found within a field of another object

Within my project, I am working with two types of objects: 'ing' containing fields 'id' and 'field', and 'fObj' containing a field named 'contain'. Using ng-repeat, I am trying to display only those ' ...

Leveraging the Mutation hook for updating information on a Graphql server

Recently, I encountered an issue while utilizing the useMutation hook in React Native to update data on my server within a project I'm working on. The file where I'm implementing this hook is attached for reference. I've also included a scr ...

React: Selecting Component Name Based on Provided Property

My goal is to dynamically load an icon component in React passed as a prop from the parent component. Dashboard (parent): import { Button } from './components'; function App() { return ( <div className="app"> <d ...

Click the toggle ng-press attribute

I have a section with an on-click="..." action. The event slightly adjusts the section's appearance within the document so that it resembles a button. I am looking to switch between making this section clickable and non-clickable in my program. While ...

How can I overlay a background image on top of another div?

This inquiry might not be the most trendy, but I am seeking guidance on the best approach to tackle this task, utilizing HTML, CSS, and Bootstrap. For reference, something similar to the image at this link. ...

Using an outdated version of Node.js to set up a React App

Attempting to utilize Create React App but encountering an issue that demands Node 10 or above. Presently, my node version is Node 8.10.0 and unfortunately, I am unable to update the Node version as it's a work device. Is there a method to operate an ...

Looking to showcase both input and output on a single PHP page?

I am working with a table that fetches rows from a database. I need to display the output of each row next to the table itself. The data for the output is also retrieved from the database. For example, when a user clicks on a particular row, I want to sho ...

Inexperienced individual asks: 'Is it possible to accomplish this task using Dojo and Ajax?'

On my website, there is a feature that sends an initial request to a web service. Once this request is sent, the user has to wait for a specific amount of time before being able to send a second request. During this waiting period, I would like a countdo ...

Align a child element to the top and another child element to the center within a flexbox column

Struggling with flexbox column and can't find a solution online! The problem: I have a full-height flex-column on the right side of my viewport with two elements (headset icon and hangup button). Trying to vertically align them - first element at top ...