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

Arranging Data in an HTML Table Using TableSorter

I have been trying to incorporate sortable columns into my HTML table and decided to experiment with the jquery tablesorter. I have followed the syntax below, but for some reason, my table is not allowing me to sort. Can you help me understand why? &l ...

What causes Jest to throw ReferenceErrors?

Question Does anyone know why I am encountering this error? ● Test suite failed to run ReferenceError: Cannot access 'mockResponseData' before initialization > 1 | const axios = require('axios'); ...

Why does the header still show content-type as text/plain even after being set to application/json?

When using fetch() to send JSON data, my code looks like this: var data = { name: this.state.name, password: this.state.password } fetch('http://localhost:3001/register/paitent', { method: 'POST&a ...

Make sure the auto import feature in TypeScript Visual Studio Code Editor is set to always use the ".js" extension

At times, the auto-import completion feature includes the .js extension, but inconsistently. When this extension is missing in the TypeScript source, the emitted JavaScript file may encounter runtime issues like module not found error since the tsc compile ...

How to use CSS to dynamically adjust the maximum width of an overflow container based on its children's content

I have a container with an overflowing <div> that displays multiple <ul> <li> lists. Each list always contains the same number of bordered <li> items, resembling a table. However, there may be instances where a <ul> has only ...

Craft a search bar inspired by Google's iconic design using CSS styling

I need to recreate a custom input styled like the Google Material Theme design. This is the desired outcome: https://i.stack.imgur.com/QU5dp.png While I am aware that frameworks/libraries can achieve this, it is part of my assignment to create it from s ...

Steps to import an excel file by clicking a button in an Angular application

Our project requires displaying an Excel file when a menu button is clicked. When a new tab is opened, I would like to showcase the Excel file that is saved on my personal computer. The format of the Excel file should resemble this: I am looking for guid ...

Encountering an issue where an error message indicates that a variable previously declared is now undefined

Currently, I am working on developing a small test application to enhance my coding skills. However, I have encountered a roadblock while attempting to display dummy information from a mongodb database that I have set up. I have tried various solutions bu ...

What methods can be used to continuously send data to another web page within my website using XMLHttpRequest()?

As I delve into working with node.js and express.js, my primary goal is to efficiently tackle a specific issue. One of the pages on my website is tasked with receiving location data in latitude var lat and longitude var long. The challenge at hand is to c ...

Transitioning create-react-app from JavaScript to Typescript

A few months ago, I began a React project using create-react-app and now I am interested in transitioning the project from JavaScript to TypeScript. I discovered that there is an option to create a React app with TypeScript by using the flag: --scripts-v ...

Pass the form data to a Bootstrap modal upon submission of the form

I'm attempting to retrieve form data and convert it to JSON to display in a modal dialog that opens on the Submit button click! This is my progress so far: HTML <form class="form-horizontal" id="configuration-form"> --irrelevant-- <button ...

There was an issue with the origin null not being permitted by Access-Control-Allow-Origin

Possible Duplicate: XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin I am currently working on a weather application that runs smoothly in browsers. However, when I try to deploy it on my Android phone, it encounters iss ...

Customizing the appearance of ASP.NET file uploader for various sizes

Has anyone successfully changed the width of the ASP.NET file uploader? I attempted by adding the CssClass, but it did not work. Is there an alternative method to adjust the width? Thanks in advance. ...

What is the best way to display the L.featureGroup using an array of coordinates?

Is there a way to render the L.featureGroup using an array of coordinateRoute from the data.json file, and then trigger it with a button labeled "Snake it!"? Essentially, I want to be able to click on "snake it!" which will have its own unique id, causing ...

Troubleshooting textarea resize events in Angular 6

In the development of my Angular 6 application, I have encountered an issue with a textarea element. When an error occurs, an asterisk should be displayed next to the textarea in the top-right corner. However, there is a gap between the textarea and the as ...

issue with padding-bottom in Firefox and Internet Explorer 11

JsFiddle CSS body, html { background: violet } * { margin: 0; padding: 0 } .fixed { height: 100%; width: 300px; background: #fff; right: 0; position: absolute; top: 0; display: -webkit-box; display: -moz-box; display: -ms-flexbox; ...

Getting the most out of Twitter Bootstrap: How to effectively implement the `.btn` class in a navbar?

Currently, I have set up a navigation bar for the usual navigation options, and now I want to include buttons for both Sign in and Sign up. To implement this, I am using an a tag with the classes btn btn-large btn-success. However, it seems that the navba ...

Unspecified data transfer between child and parent components

I'm working on implementing a file selection feature in my child component, but I'm facing difficulties passing the selected file to the parent component. I'm struggling to find a solution for this issue and would appreciate some guidance. W ...

Setting up Socket.io results in numerous transport polling GET requests being initiated

I have set up an express.js server-side and followed the socket.io guide. However, I am facing issues with the socket connection not being successful, and there seems to be a high number of unexpected GET requests like this: https://i.stack.imgur.com/GDGg ...

Warning: Promise rejection not handled in error

I've been working with nodejs, express, and argon2 in my project. However, I encountered an error that has left me puzzled as to why it's happening. Strangely, even though I don't have any callbacks in my code, this error keeps popping up. H ...