Select the top row of a table when the checkbox is ticked to emphasize it

Previously, I tackled a challenge on a webpage using jQuery where checkboxes in a table needed to be selected based on specific data attributes. Essentially, if one checkbox in a row was selected, the rest of the checkboxes would be disabled if their data attributes did not match the criteria.

Now, there's an additional requirement where I only want to highlight the first row that contains a checked checkbox at any given time.

Below is the jQuery snippet:

$(function() {
  $(".my-check").each(function(e, elem) {
    $(elem).on("change", function() {
      var num = $(this).data("number");
      var co = $(this).data("code");
      if ($(this).eq(0).is(':checked')) {
        $(this).closest('.row').addClass('highlight');
        $('.my-check:not([data-number=' + num + '])').attr('disabled', true);
        $('.my-check:not([data-code=' + co + '])').attr('disabled', true);
      } else {
        if (!$('.my-check[data-number=' + num + ']:checked').length) {
            $(this).closest('.row').removeClass('highlight');
          $(".my-check").not($(this)).attr('disabled', false);
        }
      }
    });
  })
});

See the working sample code here: Sample code here

The highlighting functionality is almost there, but it needs some tweaking. I'd like to ensure that only one row is highlighted at a time when a checkbox is checked.

Answer №1

You have incorrectly used the closest() selector. The .row should be used to search for a class name, not an element. To add color to the selected row, target the <tr> element instead.

For more details on how the closest() function works, please refer to the documentation here.

Example

$(".my-check").each(function(e, elem) {
  $(elem).on("change", function() {
    var sel = $(this);
    var num = sel.data("number");
    var co = sel.data("code");
    if (sel.eq(0).is(":checked")) {
      if (!$(".highlight")[0]) { // IF CLASS IS NOT FOUND --> Add class
        sel.closest("tr").addClass("highlight");
      }
      $(".my-check:not([data-number=" + num + "])").prop("disabled", true);
      $(".my-check:not([data-code=" + co + "])").prop("disabled", true);
    } else {
      if (!$(".my-check[data-number=" + num + "]:checked").length) {
        $('table tr').removeClass("highlight");
        $(".my-check").not(sel).prop("disabled", false);
      }
    }
  });
});
.highlight {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
    <th>Status</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
    <td><input type="checkbox" class="my-check" data-number="7867" data-code="CB45" /></td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
    <td><input type="checkbox" class="my-check" data-number="3307" data-code="HUNT1" /></td>
  </tr>
  <tr>
    <td>Harry</td>
    <td>Green</td>
    <td>50</td>
    <td><input type="checkbox" class="my-check" data-number="7867" data-code="CB45" /></td>
  </tr>
  <tr>
    <td>Mark</td>
    <td>Twain</td>
    <td>94</td>
    <td><input type="checkbox" class="my-check" data-number="5645" data-code="KLY" /></td>
  </tr>
</table>

Answer №2

function updateRowStyle(evt) {
  const action = this.checked ? 'addClass' : 'removeClass';
  $(this).closest('tr')[action]('selected-row');
}
function initializeCheckboxHandling(index, element) {
  $(element).on('change', updateRowStyle);
}
$(".my-check").each(initializeCheckboxHandling);
.selected-row {
  background-color: red;
}
.selected-row ~ .selected-row {
    background-color: initial;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
    <th>Status</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
    <td><input type="checkbox" class="my-check" data-number="7867" data-code="CB45" /></td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
    <td><input type="checkbox" class="my-check" data-number="3307" data-code="HUNT1" /></td>
  </tr>
  <tr>
    <td>Harry</td>
    <td>Green</td>
    <td>50</td>
    <td><input type="checkbox" class="my-check" data-number="7867" data-code="CB45" /></td>
  </tr>
  <tr>
    <td>Mark</td>
    <td>Twain</td>
    <td>94</td>
    <td><input type="checkbox" class="my-check" data-number="5645" data-code="KLY" /></td>
  </tr>
</table>

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

Ways to assign dynamic widths to inner divs within a parent div automatically

I am working with divs <div id='top' > <div id='top-border' > </div> <div id='top-menu' > <jdoc:include type="modules" name="top-menu" style="well" /></div> </div> and adjust ...

Understanding Multiple Type Scenarios in React with Typescript

Code Demonstration: type PropsType = {top: number} | {bottom: number} // The function that moves something in one direction by a specific distance. function move(props: PropsType) { ... } Expected Usage: move({top: 100}) or move({bottom: 100}) Avoid us ...

Enhancing JSON Objects in AngularJS with Custom Properties and Calculations

Hello, I'm still getting the hang of angularjs and could use some guidance. I have a Rest service that provides data on saleItems when a get request is made, as shown below: saleItems = [ { "id": 236, "variant": "Oval Holder", "mrp": "6 ...

Incorporate my personalized icons into the button design of ionic 2 actionSheet

I'm struggling to figure out how to incorporate my personal icon into the actionSheet feature of ionic 2/3. presentActionSheet() { let actionSheet = this.actionSheetCtrl.create({ title: 'Mode', buttons: [ { ...

Cover any HTML element with a translucent overlay box

I have a unique problem with an HTML file that is out of my control when it comes to its content. My only option is to inject a CSS file and/or JavaScript (potentially using libraries like jQuery) into the mix. Within this HTML, there are elements that re ...

Create a webpage that utilizes PHP, MySQL, and HTML to load additional content in a way similar to Facebook or the

Seeking guidance on how to incorporate pagination functionality akin to Twitter and Facebook, where a list of items loads initially and then a "load more" button appears below. When clicked, this button appends the list with additional items. Can anyone ...

Assigning background colors based on the data stored in a specific field of a MySQL database

I have successfully implemented a Ticketing System using PHP and MySQL database. The view tickets page displays each ticket from the database along with its priority level, which can be Low, Normal or High. Currently, the priority value pulled from the d ...

What is the best way to align this button next to the text and header on the page?

I'm struggling to position this button next to the paragraph element instead of below it. I want them both on the same line. <div class="up"> <div class="ban"> <div class="act"> <h2>Joi ...

Utilizing Vue.js to retrieve database information and populate input fields through select options

In my Laravel 8 and Vue 3 application, I have a Student Component with a datalist that lists all the students. My goal is to populate the input fields with the specific student information when clicking on a student. I attempted to use Vue select, which i ...

Motion of the atoms

I recently came across an interesting effect on the IconArchive website, but I am unsure how to implement it. If anyone could help me understand the concept with a small example, that would be greatly appreciated. You can see the effect in action by visi ...

What is the best way to show the probability of users' bets in percentage form based on their wagered amounts?

I am currently working on creating a Jackpot Roulette game that features a main pot. Each round sees users joining and placing bets that contribute to the main pot, with the winner taking home the entire amount. My goal is to provide each user with real-t ...

In JavaScript, merging objects will exclusively result in an identifier being returned

When working with mongoose, I have encountered an issue where combining data from multiple finds only displays the id instead of the entire object. Interestingly, when I use console.log() on the object directly, it shows all the contents. Below are snippe ...

Is there a way to utilize req.query, req.params, or req.* beyond its original scope without the need to store it in a database?

Looking to streamline my code and apply the DRY pattern, I've been working on creating a helper function for my express http methods. The structure of each method is similar, but the req.params format varies between them. Here's how I attempted t ...

What is the recommended way to adjust the width of a paper-textarea element in Polymer 1.0?

Is there a way to adjust the width of a paper-textarea? I have tried using CSS selectors within Polymer 1.0 style tags, but it does not seem to be effective. The paper-textarea element is made up of paper-input-container. I attempted the following approach ...

Troubleshooting Test Failures: The importance of passing $controller in the callback of 'it' function in Angular

As a newcomer to testing, I am attempting to write Jasmine/Karma tests for a controller. Given a sample test to use as a starting point, the issue arises when passing the $controller in the argument of the it block. The test passes successfully with this s ...

retrieving the current value of a variable from a jQuery function

I've done my best to keep things simple. Here's the HTML code I've put together: <div id="outsideCounter"><p></p></div> <div id="clickToAdd"><p>Click me</p></div> <div id="in ...

Tips for successfully passing the event in a jQuery function

I currently have four buttons on my HTML page. Create Airport Create City Create City Shortname Create Airport Shortname All of these buttons will trigger an AJAX call to the same page. Here is a snippet of the code for one of the buttons: $('#im ...

What is the best way to center a CSS arrow vertically within a table cell?

I'm having trouble with aligning a CSS arrow next to some text inside a table cell... <td><div class="arrow-up"></div> + 1492.46</td> My goal is to have the arrow positioned to the left of the text and centered vertically wit ...

What is causing the malfunction with this JQuery/AJAX request?

Currently in the process of setting up an autocomplete feature. Following the guidance from php academy at the moment. My goal is to display "suggestions go here" below the input field whenever something is typed in. I have two files for this task: home.ph ...

Experiencing issues utilizing vue.js to retrieve information from a REST API

Using vue.js, I am attempting to fetch data from a rest api but encountering issues. Unfortunately, the response data is not being displayed and no error status is shown either. It's puzzling trying to identify what may have gone wrong. Below is my i ...