A method for evaluating the condition of a <td> value in a table based on its corresponding table header

I am looking to modify the th and td values in my HTML code. Specifically, I want to align numbers to the right (except for s.no) and text to the left.

 <button type="submit" class="btn btn-raised btn-primary mr-5"
   (click)="productPrintSection('productSection')">
     <i class="fa fa-check-square-o"></i> Print
    </button>

The following is my HTML code, where the data is dynamically populated:

 <div id="invoice-items-details" class="pt-2">
  <div class="row">
 <div class="table-responsive col-sm-12">
   <table class="table">
    <thead>
     <tr>
     <th 
     *ngFor="let column of productColumns">
       {{column.name}}
     </th>
     </tr>
    </thead>
    <tbody>
    <tr  *ngFor="let list of productSource; let i=index">
     <td 
        *ngFor="let column of productColumns">
           {{ list[column['value']] }}
      </td>
      </tr>
     </tbody>
     </table>
    </div>
   </div>

My print section code is as follows:

productPrintSection = function (reportSection) {
    let printContents, popupWin;
    printContents = document.getElementById(reportSection).innerHTML;
    popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
    popupWin.document.open();
    popupWin.document.write(`
    <html>
    <head>
    <style>
      body { width: 99%;}
        h1 {
             text-align:center;
           }

        ul {
            list-style: none;
            padding: 0;
            margin: 0;
           }
        label { font-weight: 400;
                font-size: 13px;
                padding: 2px;
                margin-bottom: 5px;
              }
        table, td, th {
                        border: 1px solid silver;
                      }
                table td {
                          text-align: center;
                          font-size: 13px;
                         }

                 table th {
                          font-size: 13px;
                          }
        table {
                border-collapse: collapse;
                width: 98%;
              }
        th    {
                height: 26px;
              }
    </style>
    </head>
            <body onload="window.print();window.close()">${printContents}</body>
    </html>`
    );
    popupWin.document.close();
}

Here is a link to view my output screen:https://i.sstatic.net/CJTg8.jpg

Can you please advise me on how to align numbers to the right (except for s.no) and text to the left?

Answer №1

After not being able to find a CSS selector for targeting cells with numbers in them, I decided to create a JavaScript function that checks if the content of a cell can be converted into a number using !isNaN(col.innerText). Simply invoke the styleTable function whenever it is needed.

Here is an example snippet based on the code you provided:

var table = document.getElementById("products");

window.onload = function() {
  styleTable(table)
};


function styleTable(table) {

  //loop through the second row to check what kind of value they have
  for (var i = 1, row; row = table.rows[i]; i++) {
    //exclude the first column "S.no"
    for (var j = 1, col; col = row.cells[j]; j++) {
      //check if the column value is a number
      if (!isNaN(col.innerText)) {
        col.style.textAlign = "right";
      }
    }

  }
}
body {
  width: 99%;
}

h1 {
  text-align: center;
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

label {
  font-weight: 400;
  font-size: 13px;
  padding: 2px;
  margin-bottom: 5px;
}

table,
td,
th {
  border: 1px solid silver;
}

table td {
  text-align: center;
  font-size: 13px;
}

table th {
  font-size: 13px;
}

table {
  border-collapse: collapse;
  width: 98%;
}

th {
  height: 26px;
}
<table id="products">
  <tr>
    <th>S.no</th>
    <th>Product Name</th>
    <th>Product code</th>
    <th>Purity</th>
    <th>Store</th>
    <th>city</th>
    <th>state</th>
    <th>quantity</th>
    <th>weight</th>
    <th>total</th>
    <th>total orders</th>
  </tr>
  <tr>
    <td>1</td>
    <td>xyzzy</td>
    <td>1001010</td>
    <td>54.00</td>
    <td>Default</td>
    <td>Hyderabad</td>
    <td>dashdsaf</td>
    <td>10</td>
    <td>2135.5000</td>
    <td>239280324.09</td>
    <td>12</td>
  </tr>
  <tr>
    <td>2</td>
    <td>xyzzy</td>
    <td>1001010</td>
    <td>54.00</td>
    <td>Default</td>
    <td>Hyderabad</td>
    <td>adsfsdf</td>
    <td>0</td>
    <td>2135.5000</td>
    <td>239280324.09</td>
    <td>13</td>
  </tr>
</table>

I hope this information proves useful!

Edit:

I've included a more dynamic approach to styling each cell accordingly.

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

Transferring input data between two HTML files in Electron with a secure login feature

Currently, I am in the process of developing an Electron app that facilitates communication between users through socket.io. The app includes a login screen where users can enter their registered email and password to access the main menu. For testing purp ...

Optimizing the particle rendering speed for HTML5 <canvas> elements

Currently conducting an experiment to enhance the maximum particle count before frame-rates begin to decrease in HTML5 Canvas. Utilizing requestAnimationFrame and employing drawImage from a canvas as it appears to be the most efficient method for image re ...

Showing a generated content before element on a progress bar using the ::before pseudo-class

I'm currently attempting to showcase a ::before pseudo-element on a <progress> bar in the form of a label featuring the value attribute. My current approach successfully displays the ::before element in Brave (v1.61.109), but unfortunately, it d ...

Troublesome alignment with bootstrap grid system

I require some assistance with the following: https://i.sstatic.net/vK9zmm.png Specifically, I need help regarding the structure shown below: <div class="row"><div class="col-md-4"> <a class="individ" href="index.p ...

How to remove checkbox border using HTML, JavaScript, and CSS

Is it possible to remove the square border from a checkbox in HTML? ...

Change the way a button interacts with a different element

Currently, I am utilizing SlickSlider from http://kenwheeler.github.io/slick/ and attempting to integrate the Next and Prev buttons with other elements (specifically spans within another container). I have attempted the following: $('button.next&apo ...

Is it possible for a DIV in one bootstrap column to appear on top of the content in another column?

Is there a way to get a div in the first bootstrap column to overflow the x-axis and have its content display above the second column to the right? <div class="row h-100"> <div class="col-3 bg-info"> <div class="LEFT ...

Unusual sequence of JQuery Ajax calls

Within my website, there is a project div that is displayed using EJS. The data for the projects in EJS are rendered using a forEach loop, resulting in multiple similar divs appearing on the page. Each project div is assigned an id for identification pur ...

The functionality of the onclick and onserverclick attributes seem to be malfunctioning when

I am in the process of creating a basic login screen using the code provided below: <form id="login"> <div class="formHeader"> <h1>Login</h1> </div> <div class="formDiv"> <input type="text" placeholder="Email" na ...

Automatically adjust the image size in CSS to fit the screen when the iPhone is rotated from portrait to landscape

I am trying to create a responsive design where an image will fit the screen without being cropped in both portrait and landscape mode. I have attempted the following code: <!doctype html> <html> <head> <style> img { max-height ...

The font implemented in Bootstrap does not appear to be adapting well to different

As I embark on the Bootstrap journey, I find that everything looks great on my desktop browser in terms of responsiveness. However, when I switch to my iPhone 6, it doesn't seem to display as expected... Provided below are a few screenshots: Desktop ...

Is there a way for me to choose every element excluding those contained within a specific div?

Check out my code snippet: <div class="car"> <div class="make">NISSAN</div> <div class="model">MICRA</div> </div> <div class="discontinued"> <div class="car"> <div class="make">FOR ...

Outline along a single edge

Is there a way to add an inset border to an HTML element on just one side, without using an image as a background? I've been stretching and positioning images for this purpose in the past, but I recently discovered the outline CSS property. However, i ...

Engaging with JSON data inputs

Need help! I'm attempting to fetch JSON data using AJAX and load it into a select control. However, the process seems to get stuck at "Downloading the recipes....". Any insights on what might be causing this issue? (Tried a few fixes but nothing has w ...

Executing a Javascript function when a form is submitted

function validateForm() { alert("Form submitted successfully"); return true; } <form onsubmit="return validateForm()" action="add.php" method="post" id="p1"> <center>Add New Survey</center> <p>&nbsp;&l ...

Unable to adjust font for headings using CSS and Bootstrap

Looking to expand my skills in HTML and CSS, I've encountered a bit of a hiccup. Utilizing Bootstrap for my webpage, here's the simplified version of what I have so far: index.html: <!DOCTYPE html> <html> <head> <lin ...

Display advertisement in full screen on mobile devices with no need for scrolling bars

I am looking to develop a webpage using HTML/CSS/Javascript that can display an advertisement in full screen on mobile devices like smartphones and tablets. The ad should expand to the maximum width and height of the screen without any scrollbars. I have ...

Using JavaScript, what is the method for inputting values into a window.prompt()?

I've been working on a project that involves scraping basic HTML pages from an internal server at my workplace. When I visit these pages, a popup window similar to a windows.prompt() appears, asking for a username and password with the message "Enter ...

The placeholder attribute for input types does not display consistently across all browsers

I am experiencing an issue with the placeholder text in my input field. <input type="text" name='linkLabel{{index}}' autocomplete="off" class="input-large tight-form-url last remove-cross" required="required" placeholder="{{'linkLabel&ap ...

Display the widget beyond the boundaries of the sidebar

Currently, I am using my own custom theme called Total. I want to display the Sidebar Login plugin's widget in the header section of my website. I attempted to do this with the following code: <div class="login"><?php the_widget('sideba ...