What is the best way to stop a jQuery function from applying titles extracted from the first row th's in thead's to multiple tables in a document?

My circumstances: I am new to jQuery and Stack Overflow, seeking assistance for my website project.

The challenge: Building a website using Bootstrap 3.3.6 with intricate data tables that need to be stacked dynamically on mobile devices using CSS. It is crucial for the column headers to be repeated for context. Additionally, as the website is bilingual, I require control over the mobile table header text.

The proposed solution involves a jQuery function that captures custom headers from the title attribute of each table's first row th element and adds them to the corresponding td elements within the tbody section using the CSS content property.

The hitch: The current function works effectively when there is only one table in the document. However, if there are multiple tables present, it mistakenly applies the titles from the first table to all tables.

Objectives: 1) Assign unique id attributes solely to tables requiring the aforementioned function. 2) Exclude tables without an id attribute. 3) Ensure the function retrieves and assigns the correct titles to their respective table tbody sections. 4) Address any potential conflicts with other scripts such as Modernizr or prettyPhoto.

For reference, here is the JSFiddle link showcasing the progress made so far: current script

(function() {
    "use strict";
    var tableIds = Array();
    $('table').each(function(tid) {
        if (tableIds) {
            tableIds[tid] = $(this).attr('id');
        }
        var currentId = tableIds[tid];
        alert('Id is: ' + currentId);
    });

    var header = Array();
    /*get titles from the headings*/
    $('thead tr:first-child th').each(function(i) {
        if (header) {
            header[i] = $(this).attr('title');
        }
    });
    /*loop through tbody rows and apply headings to each td*/
    $('tbody tr').each(function() {
        var thRow = $(this);
        thRow.find('td').each(function(j) {
            $(this).attr('title', header[j]);
        });
    });
}());

Answer №1

In order to apply a title to the tables as shown below, simply add the class applyHeader to the table you wish to have the title for headers:

<u>Table1</u>
<table class="applyHeader">
  <thead>
    <tr>
      <th title="header11">header1</th>
      <th title="header12">header2</th>
      <th title="header13">header3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>col11</td>
      <td>col12</td>
      <td>col13</td>
    </tr>
  </tbody>
</table>
<br>
<u>Table2</u>
<table class="applyHeader">
  <thead>
    <tr>
      <th title="header21">header1</th>
      <th title="header22">header2</th>
      <th title="header23">header3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>col21</td>
      <td>col22</td>
      <td>col23</td>
    </tr>
  </tbody>
</table>
<br>
<u>Table3</u>
<table >
  <thead>
    <tr>
      <th title="header31">header1</th>
      <th title="header32">header2</th>
      <th title="header33">header3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>col31</td>
      <td>col32</td>
      <td>col33</td>
    </tr>
  </tbody>
</table>

To achieve this, use the function provided below:

   (function() {
      "use strict";
      $('table.applyHeader').each(function() {
          var tableSelected=this;
      $(this).find('th').each(function(index) {
       var headerTitle = $(this).attr('title');
       $(tableSelected).find('tbody').find('td').eq(index).attr('title',headerTitle);
      });
      });

  }());

UPDATE: - Jsfiddle Demo Link

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

Looking to update the background color of the items in a sliding door menu using CSS

I'm having trouble changing the background color of my list items in a sliding door menu using CSS. I've successfully changed the left border to green and the text to white, but the background color remains unchanged. Below is the code I'm u ...

What is the best way to test for errors thrown by async functions using chai or chai-as-promised?

Below is the function in question: async foo() : Promise<Object> { if(...) throw new Error } I'm wondering how I should go about testing whether the error is thrown. This is my current approach: it("checking for thrown error", asy ...

Utilize React HOC (Higher Order Component) and Redux to retrieve data and pass it as props

In my quest to develop a Higher Order Component (HOC) that can execute methods to fetch data from the backend and display a loader mask during loading, I encountered a challenge. I aim to have the flexibility of passing different actions for various compon ...

The XMLHttpRequest is displaying additional characters within its response

Upon completing an XMLHttpRequest(), I am receiving the unexpected output of "true↵↵↵". In my php file, all I have is echo json_encode(true); Can anyone shed some light on why this strange behavior is occurring? Thank you ...

Design inspired by dot matrix patterns

Is it possible to create a background HTML page filled with a dot matrix designing tool? Can anyone provide guidance on how to achieve this? If I need to use a background-image for this, where can I find the appropriate picture? Thank you to everyone in ...

Is there a difference between $('li.item-ii').find('li') and $('li.item-ii li') in jQuery?

Looking at the example of jQuery's find() (documentation can be found here) I am curious about its necessity, as $('li.item-ii').find('li') seems to be equivalent to $('li.item-ii li') In essence, both select all ...

Issue: Retrieve comments via AJAX (from database) in Laravel 5.2

Currently, I am developing a comments section for posts where users can leave comments without the need to refresh the page. However, I am facing an issue in displaying these comments instantly on the post without any page refresh. This is how I have stru ...

The issue with collapsible elements not functioning properly in an Angular application involving CSS and JS

My implementation of collapsible in a plain HTML page looks like this: <!DOCTYPE html> <html> <head> <title></title> <style> button.accordion { background-color: #777; color: white; cursor: pointer; p ...

Is there a way to customize the primary column in Material-table?

I am utilizing the Material-table and I am in need of rearranging the column index to be at the end of the table as the default position for this column (actions) is at the beginning. Here is the code snippet for the table: <MaterialTable title=" ...

Issue with jQuery DataTables column.width setting failing to meet expectations

Currently, I am utilizing datatables for my project. According to the datatables documentation found here, it suggests using the columns.width option to manage column width. However, when I implement columns.width and render the table, it seems to disreg ...

Converting jQuery ajax success response data into a PHP variable: A step-by-step guide

When sending data to a php page for processing using jQuery and ajax, I receive a response in the form of: success: function(data){ mydata = data; } The data retrieved is a URL represented as mydata = https://myurl.com. Now, I want to assign this data to ...

Can adjusting the viewport by using touch controls alter the size of the viewing screen?

When I tried to zoom in on a webpage using touch instead of the keyboard shortcut Ctrl +, I noticed that the elements stayed the same size but the screen itself was enlarged. It seems like this method does not affect the size of the viewport. However, whe ...

Using HTML within a Material-UI Accordion component

I am attempting to display HTML content within an Accordion component. import {Accordion, AccordionDetails, AccordionSummary, Typography} from '@material-ui/core'; import { Badge } from 'reactstrap'; ... const buildAccordion = (f, i) ...

Bootstrap 4 Carousel with Multiple Items

I am looking to create a carousel that can display multiple items or images at once. The carousel should show 4 items initially, and when I click on 'next', the next item should appear, and so forth. Below is an image depicting what I have in min ...

Error: The callback specified is not a valid function

Here is a function example: reportAdminActions.reportMemberList(project, function(data) { console.log(data); }); This particular function gets called by another ajax operation, similar to the one shown below: reportMemberList: function(projectId, ca ...

Generating a hierarchical structure of JSON data through iterative looping

Currently, I am in the process of creating a directive within Angular to assist with field validation. The functionality is working smoothly until it comes time to store the validation result. My objective is to store this information in an object structu ...

Unable to assign the value 'hello' to an undefined property in TypeScript

I'm attempting to define a class in TypeScript, but I keep encountering the error shown below. Here is the execution log where the error occurs: [LOG]: "adding" [LOG]: undefined [ERR]: Cannot set property 'hello' of undefined class Cust ...

"Firebase offers the flexibility to have several 'apps' configured, both on the client side and the server

Currently, I have a firebase app set up in my project for SSR using firebase-admin. However, I now want to add firebase@8 to be able to utilize it on the client-side and eventually apply firestore rules. The issue arises when I try to use firebase@8, I enc ...

PhpStorm 2019.2 introduces Material UI components that have optional props instead of being mandatory

My PhpStorm 2019.2 keeps showing me a notification that the Button component from Material UI needs to have an added href prop because it is required. However, when I refer to the Material UI API, I see something different. Take a look at this screenshot: ...

The functionality for inserting data via Ajax in WordPress is failing

Greetings, I am currently in the process of developing a popup plugin for WordPress that involves inserting data into a database using AJAX. Everything in my code is functioning correctly up until the jQuery section, where the data fails to insert into the ...