Adjust the dimensions of the thead, tbody, and td elements on the fly

I've implemented this property in a .css file on the table shown below and there are 9 records.

   .fixed tbody td, thead th {
    width: 5.2%;
    float: left;
    }

In my scenario, when there are 4 columns, the width should be 23.2%; for 5 columns, it should be 18.2%; for 6 columns, 16.2%; for 7 columns, 14.2%; and for 8 columns, 12.2%. However, more columns may be added in the future. How can I dynamically manage the column widths without them increasing or decreasing sequentially?

Answer №1

If you're looking to assign an equal width to each column in a table without knowing the number of columns beforehand, there's a simple solution.
Simply divide the total width of the table by the number of columns present.

$(document).ready(function(){

  // Specify the table to target.
  var table = $("table.fixed")

  // Get the width of the table.
  var tableWidth = table.width();

  // Collect the cells in the first row.
  var firstRowTdCollection = table.find("tr").first().find("td");

  // Determine the number of columns.
  var columnCount = firstRowTdCollection.length;

  // Calculate the desired width based on the table width and column count.
  var widthToApply = tableWidth / columnCount;

  // Apply the calculated width to the cells in the first row (no need to apply to other rows).
  firstRowTdCollection.each(function(){
    $(this).width(widthToApply);
  });
});

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

The positioning and floating of two divs are set to fixed without using percentage width, however, the functionality is not

Apologies for my poor English writing :) I am attempting to float two divs side by side in a fixed position, without using percentages. This code works well on most browsers but is not compatible with IE 6. HTML <div class="right"></div> < ...

Build a Search Suggestions feature with Node Package Manager (NPM) and Model-View-Controller (M

Stepping into the exciting world of MVC core and harnessing NPM for JavaScript packages has been a learning curve. However, I've encountered an issue that requires some deliberation on the best course of action for resolution. To provide context, I ha ...

What is the most efficient method for fetching data from the server at regular intervals of 30 minutes?

As I search for a way to automatically update my webpage with fresh data from the server, I am faced with uncertainty regarding the frequency of these updates. The intervals could range anywhere from every 10 minutes to an hour, which makes it challenging ...

Creating a customized URL using the famous "@" symbol

Is it possible to set up a dynamic route in Next.js that includes the @ symbol? For instance, localhost:3000/@some_username I'm familiar with creating dynamic routes using the pages folder, but I'm not sure how to achieve this specific format w ...

The protection ensured by employing an extensive hash in the query string for the recognition of a changing document

I am currently developing a small web application that creates exercise program printouts. The concept is simple - a user like a personal trainer can craft an exercise regimen and send it to their client via email using a unique link. http://www.myurl ...

What is the best approach for handling errors in a NestJS service?

const movieData = await this.movieService.getOne(movie_id); if(!movieData){ throw new Error( JSON.stringify({ message:'Error: Movie not found', status:'404' }) ); } const rating = await this.ratingRepository.find( ...

Calculate the average value of the properties of a jQuery object

Consider the object below: rating { atmosphere: 85 cleanliness: 91 facilities: 91 staff: 85 security: 94 location: 78 valueForMoney: 85 } I'm looking to calculate the average of all these property values. Can y ...

Transform a base64 image into a blob format for transmission to the backend via a form

Is there a way to convert a base64 string image to a blob image in order to send it to the backend using a form? I've tried some solutions like this one, but they didn't work for me. function b64toBlob(b64Data, contentType='', sliceSiz ...

The navigation bar appears to have a different width on mobile view specifically on one page

I created a mobile view navigation that appears correctly on two out of three pages. It spans the full 100% width as intended, but on one page it extends beyond that and causes the layout to look distorted due to the larger navigation bar. I'm not sur ...

The data received from the frontend is being replicated in the backend, causing duplication issues in a React

Whenever I click the button labeled onClick, it triggers the transmission of data (both time and ID) to the backend. The issue at hand is that the backend seems to be receiving the data twice instead of just once. On inspecting req.body, it becomes eviden ...

Loading message displayed in web browsers by banner rotation system

I'm currently working on a banner rotator function that seems to be showing a "loading" message continuously while running. Here is the code snippet for reference: var banners = ['../Graphics/adv/1.gif','../Graphics/adv/2.jpg']; / ...

``There seems to be an issue with the functionality of the href link

Currently, I am utilizing purecss to design colorful buttons on my website. However, I am encountering an issue where the href link is not clickable even though the button displays correctly. <button class='pure-u-1 pure-button pure-button-primary ...

Struggling with PHP variables and AJAX JavaScript

Hey everyone, I've made some edits and have a new question regarding a similar issue. On test.php in my Apache server, I have a PHP script that connects to a database and retrieves data from a table. <?php $con = mysqli_connect("localhost", "user" ...

Add option button

Is there a way to dynamically add radio buttons using jQuery or JavaScript and save the data into a database? I have successfully appended input types such as text, textarea, checkbox, and select with options. Here is my code: <!DOCTYPE html> < ...

Is there a way to animate without specifying a duration?

Exploring the capabilities of the Animated component in react-native, I came across the powerful Animated.timing(); function which operates within a specific duration defined as duration: 2000,. While duration is useful in certain scenarios, I found myself ...

What to do when encountering the error "Uncaught (in promise) SyntaxError: Unexpected end of JSON input"?

While signing in to my website from localhost is successful, I encounter an issue when trying to do the same from my production build. The login attempt from the prod build (hosted on Vercel) does not post to , but instead goes to . I am perplexed by the a ...

A guide to utilizing the Eric Hynds idle timeout plugin

I came across a plugin called this one, designed by Eric Hynds, that displays a message asking users if they want to continue with their session or if it will time out. Essentially, if a user is idle for a certain period of time, the plugin prompts them to ...

What are effective ways to eliminate script tags from a webpage?

I have implemented tags on my website that users can use to interact with the site. My goal is to figure out how to make the browser only read text from a specific file I write, without any HTML. This should be restricted to certain sections of my websit ...

Efficiently search and filter items across multiple tabs using a single search bar in the Ionic 2

I am currently working on implementing a single search bar that can filter lists in 2 different tabs within Ionic 2. The search bar is functional, and I have a method for filtering through objects. However, my goal is to allow users to select different tab ...

Emphasize the current page's menu item for the user viewing it

I'm looking for a way to visually emphasize the current menu item so that users can easily identify the page they are currently on. This could be achieved through bolding or underlining, whichever works best. I'm hoping to accomplish this using o ...