Highlighting a Table Column with a Radio Button

I am struggling with controlling the highlight of a table using only radio buttons. When I try to change the selector to input:radio, it doesn't work as expected. It seems to only work with the selector provided in my code snippet.

$("th").on("click", function () {
  var $currentTable = $(this).closest("table");
  var index = $(this).index();
  $currentTable.find("td").removeClass("selected");
  $currentTable.find("tr").each(function () {
    $(this).find("td").eq(index).addClass("selected");
  });
});
table tr td {
  width: 5em;
}
.selected {
  background-color: limegreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="options" border="1" cellpadding="0" cellspace="0">
  <tr>
    <th><input type="radio" name="test" value="1" /></th>
    <th><input type="radio" name="test" value="2" /></th>
  </tr>
  <tr>
    <td>col_1</td>
    <td>col_2</td>
  </tr>
  <tr>
    <td>col_1</td>
    <td>col_2</td>
  </tr>
  <tr>
    <td>col_1</td>
    <td>col_2</td>
  </tr>
  <tr>
    <td>col_1</td>
    <td>col_2</td>
  </tr>
</table>

Answer №1

When changing to radio-buttons, it is important to listen for the change event in order to determine when the button has been checked. Additionally, the use of the this keyword will refer to the button itself, not the th, requiring you to locate the correct th to obtain the accurate index.

Take a look at the example provided below:

$("input[name='test']").on("change", function () {
  var $currentTable = $(this).closest("table");
  var index = $(this).closest('th').index();
  $currentTable.find("td").removeClass("selected");
  $currentTable.find("tr").each(function () {
    $(this).find("td").eq(index).addClass("selected");
  });
});
table tr td {
  width: 5em;
}
.selected {
  background-color: limegreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="options" border="1" cellpadding="0" cellspace="0">
  <tr>
    <th><input type="radio" name="test" value="1" /></th>
    <th><input type="radio" name="test" value="2" /></th>
  </tr>
  <tr>
    <td>col_1</td>
    <td>col_2</td>
  </tr>
  <tr>
    <td>col_1</td>
    <td>col_2</td>
  </tr>
  <tr>
    <td>col_1</td>
    <td>col_2</td>
  </tr>
  <tr>
    <td>col_1</td>
    <td>col_2</td>
  </tr>
</table>

Answer №2

Your issue lies in the following code snippet:

var index = $(this).index();

The current implementation retrieves the index value of the input element, instead of its parent element. To fix this, update the code to:

var index = $(this).parent().index();

It's worth noting that while you can use the click event, the change event is more suitable.

$("input[name='test']").on("change", function () { // You can also use clicks, but the change event is better for radio/checkbox inputs
  var $currentTable = $(this).closest("table");
  var index = $(this).parent().index(); // Get the parent's index
  $currentTable.find("td").removeClass("selected");
  $currentTable.find("tr").each(function () {
    $(this).find("td").eq(index).addClass("selected");
  });
});
table tr td {
  width: 5em;
}
.selected {
  background-color: limegreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="options" border="1" cellpadding="0" cellspace="0">
  <tr>
    <th><input type="radio" name="test" value="1" /></th>
    <th><input type="radio" name="test" value="2" /></th>
  </tr>
  <tr>
    <td>col_1</td>
    <td>col_2</td>
  </tr>
  <tr>
    <td>col_1</td>
    <td>col_2</td>
  </tr>
  <tr>
    <td>col_1</td>
    <td>col_2</td>
  </tr>
  <tr>
    <td>col_1</td>
    <td>col_2</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

What's the best way to ensure that the theme state remains persistent when navigating, refreshing, or revisiting a page in the browser?

Is there a way to ensure that my light/dark theme settings remain persistent when users reload the page, navigate to a new page, or use the browser's back button? The current behavior is unreliable and changes unexpectedly. This is the index.js file ...

Is it considered best practice to call the same function within itself in a function?

function takeANumber() { let startHealth = parseInt(prompt("Please enter a positive number:")); // I am recursively calling the same function within an if block to ensure that the input is a valid number greater than zero. Is this considered good practic ...

Having trouble retrieving the accurate height value for the UIWebView

Currently, I am attempting to retrieve the value of a UIWebView using the following approach: var webview = self.articleContent println(webview.frame.size.height) // This outputs 300 // Now rendering the w ...

"Encountered a Json error with a bizarre character causing the string

After extracting some json data from a website, I encountered an issue when trying to parse it using vscode. I kept getting an 'unexpected end of string' error on the "content" line: Here is the json: { "name": "Anna Vergnas", "date" ...

Express JS routing encounters 500 error following the submission of a form button

I've been developing a unique chatbot that specializes in recommending songs based on the user's current mood. However, I've hit a roadblock when it comes to routing a response to the user after they submit their preferences through an HTML ...

What is the process of dynamically creating a Javascript object?

I have been experimenting with creating the following custom array: var deal_info = { "1": { "deal": { "deal_id": "1", "qty": "1", "option_price_sale": "7900", "price_ship": "2500", " ...

Tips for efficiently resolving and compiling a bug within an NPM package, ensuring it is accessible to the build server

This question may seem a bit unconventional. I am currently using an npm package that includes built-in type definitions for TypeScript. However, I have discovered a bug in these definitions that I am able to easily fix. My goal is to make this updated ve ...

What are some of the potential drawbacks of utilizing the same template ref values repeatedly in Vue 3?

Is it problematic to have duplicate template ref values, such as ref="foo", for the same type but different instances of a component across views in a Vue 3 application? Let's consider the following example pseudocode: // ROUTE A <te ...

"Troubleshooting 3D Models not appearing correctly in Mapbox when using Three.js

My issue lies in the inability to load any .gltf file, only a standard one. For further details, please continue reading. The map on my application showcases a 3D model indicated by the red arrow: https://i.sstatic.net/3Ce09.png The model is a GLTF file ...

Automatically submitting Ajax form upon loading the page

I am attempting to use ajax to automatically submit a form to a database upon page load. The form and php code work perfectly when manually submitted, but for some reason, the ajax function does not trigger. Despite checking the console for errors and con ...

AngularJS - Regular Expression Error

I have implemented a RegEx pattern to validate passwords entered by users. The password must contain at least 1 capital letter, 1 number, and 1 symbol: /(?=.*?\d)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[^a-zA-Z\d])/ When this RegEx is used with ng-patter ...

Having trouble with the alias in commander.js not functioning as desired when using the "--help" option

Currently, I am facing a strange issue while working on my project with commander.js. The problem arises when assigning an alias for a command. I looked at some examples mentioned in the reference: Commander.JS Example I decided to create a git-like comma ...

Putting text on top of an image using Bootstrap

Recently diving into the world of Bootstrap, I have come across a puzzling issue: Take a look at the HTML code from my website: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width ...

Having trouble with Vee-validate Basic example - undefined errors issue

I've been struggling to get a basic form validation page working with vee-validate. Something seems to be going wrong, but I can't pinpoint the exact issue. Why am I seeing the error: errors not defined. <!DOCTYPE html> <html> < ...

Encountering problems when trying to mock values with Jest

I'm currently integrating Jest into an existing project that is already utilizing enzyme and jasmine. Although I have installed the jest packages and configured them initially, I am facing an issue where the mock data is not being supplied correctly. ...

The function dispatch is not recognized and will be removed from the database. An error will be generated indicating that dispatch is not a valid function

There seems to be an issue with the delete function in Ticket Actions as it is giving an error that dispatch is not a function. The goal here is to enable users to delete specific tickets by clicking on them and also provide an option to edit the ticket. ...

Creating an overlay button within various containing divs requires setting the position of the button

Tips for overlaying a button on each HTML element with the class WSEDIT. My approach involves using a JavaScript loop to identify elements with the CSS class WSEDIT, dynamically create a button within them, and prepend this button to each element. Below ...

I encountered an issue while trying to integrate react-alert into my React application. An Uncaught Error was thrown, stating that objects are not valid as a React

I encountered the following error: react-dom.development.js:14748 Uncaught Error: Objects are not valid as a React child (found: object with keys {$$typeof, render}). If you meant to render a collection of children, use an array instead. in Unknown (c ...

Ways to display an error message in Angular 8 when entering anything other than numbers in a text box

In my Angular 8 application, I have a text box that only allows the user to type numbers. If they try to type an alphabet or special character, it should display an error message below the text box. The error message should disappear once the user starts ...

Tips for managing both DOM manipulation and state changes at the same time in AngularJS

<div my-custom-directive> <button id="myButton" ng-click="handleClick(mymodel.id)"><button> </div> app.controller('myCtrl', function($scope) { $scope.handleClick = function(id) { //Perform state change here without ...