Adjusting Javascript code to convert numerical values in HTML table cells from thousands to millions

Does anyone know how to create a Javascript function for a web report that converts table values to thousands or millions by dividing or multiplying by 1000?

The issue is that each value is clickable, meaning it is wrapped in an anchor tag.

Is there a way to achieve this?

<table class="Table" >
<thead><tr>
  <th class="l Header" scope="col">£000s</th>
  <th class="l Header" scope="col">Col1</th>
  <th class="l Header" scope="col">Col2</th>
</tr></thead>
<tbody>
<tr>
  <td class="l Data">   My Data Row </td>
  <td class="l Data">   <a class=nums href="javascript:MyFunc();">  11,372,397</a></td>
  <td class="l Data">   <a class=nums href="javascript:MyFunc();">  11,344,327</a></td>
</tr>
</tbody>

edit

I am using IE6. The goal is to have buttons for 'thousands' and 'millions' so that the table values can be displayed as 11,372k or 11.4m, etc.

Answer №1

If I were to choose a library, I'd go with jQuery

$(function (){
    $.each($('.nums'), function () {
        $(this).html(Number($(this).html().replace(/,/g,"")) /*your calculation here*/);
    });
});

Regarding your recent revision: Feeling a bit bored, I whipped up this functional code snippet for you to play around with, rounding and adding commas as desired.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

<table class="Table" >
<thead><tr>
  <th class="l Header" scope="col">£000s</th>
  <th class="l Header" scope="col">Col1</th>
  <th class="l Header" scope="col">Col2</th>
</tr></thead>
<tbody>
<tr>
  <td class="l Data">   My Data Row </td>
  <td class="l Data">   <a class="nums" href="javascript:MyFunc();">  11,372,397</a></td>
  <td class="l Data">   <a class="nums" href="javascript:MyFunc();">  11,344,327</a></td>
</tr>
</tbody>

<input type="button" onclick="toMillions();"> 
<input type="button" onclick="restore();"> 

<script type="text/javascript">

    $(function (){
        $.each($('.nums'), function () {
            $.data(this, "theValue", $(this).html());
        }); 
    });


    function toMillions(){
        $.each($('.nums'), function () {
            $(this).html(Number($.data(this,"theValue").replace(/,/g,"")) / 1000000 + ' million');
        });
    }

    function restore(){
        $.each($('.nums'), function () {
                $(this).html($.data(this,"theValue"));
        });
    }
</script>

Answer №2

One approach could be to consider using document.getElementsByClassName('numbers'), as it will provide you with an array of the elements you need. Here is an example of how you could achieve this:

numbers = document.getElementsByClassName('numbers');
for (index in numbers)
   numbers[index].innerHTML = numbers[index] + ',000';

This method may be more compatible with newer browsers, so you might want to explore similar techniques in a javascript framework. For instance, jQuery offers a way to select elements by class name like so:

$('.numbers')

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

Tips for allowing specific tags using Google's Caja HTML Sanitizer in a node.js environment

I'm currently utilizing the npm module Caja-HTML-Sanitizer with node.js. Although I am able to sanitize the HTML input using the sanitizer() function, I am unsure of how to implement a whitelist in order to restrict only certain tags (e.g. p br stron ...

What is the best way to implement a new search input for my datatable while also enabling the searchHighlight feature?

I'm attempting to implement a search bar for my datatables. I need to hide the default search engine that comes with datatables, so I added a script that I found in a forum. However, when I try to run it in my code, it doesn't work and displays a ...

How can I center an element on the screen using CSS positioning?

Here is the CSS code that I am using, defined in the React Material-UI withStyles method: const styles = (theme: Theme) => { return ({ display: { transition: theme.transitions.create('transform') }, dis ...

Is there a way to make elasticX() and elasticY() only affect the upper bound in dc.js?

One question I have regarding my bubbleChart in dc.js is related to the x-axis. I want the count on the x-axis to always start at 0, but have an upper bound that adjusts based on the range I am looking at. Currently, when I use .elasticX(true), both the up ...

The inclusion of float: left disrupts the formatting of the list

My webpage features a visual element known as a "plan", which consists of a small table and an image. I want these two elements to appear side by side without any styling. Currently, they are displayed one below the other. You can view how it looks like he ...

Displaying an array in a tabular format using PHP

My PHP Project involves printing a sorted array in table format without using premade sorting functions. The current sorting function works, but the data does not display correctly in the table. The code provided sorts the array and tries to output it in a ...

Mobile site experiencing slow scrolling speed

The scrolling speed on the mobile version of my website, robertcable.me, seems to be sluggish. Despite conducting thorough research, I have not been able to find a solution. I have attempted to address the issue by removing background-size: cover from my ...

Storing a webpage in HTML with the use of @import function in CSS

I'm looking to save an entire HTML page, but I'm running into an issue with the CSS file that includes the line: import url('someOtherCss.css'); When attempting to save the page using Firefox or Chrome with 'File->Save Page a ...

What is the best method for arranging multiple images in a grid while keeping them within a specific maximum width and height?

I've been staring at this problem for a while now, attempting every possible solution to resize images and maintain aspect ratio, but none seem to work in my case. Here are two images that I manually resized so you can view them side by side: highly ...

Crafting an interactive form

Creating a form with 2 options (Yes/No) is my current task. When the user selects one of these options, I want a collapsible subform to appear with specific details related to that selection. If the user chooses the other option, a different collapsible su ...

Auth0 encountering issues retrieving ID token and user metadata

Currently in the process of integrating Auth0 into a Vue.js/Node.js application, I have successfully enabled user registration and login functionality (to /callback). Although the manual addition of data to the user metadata section is functional at this s ...

Support the Cause with Paypal Contributions on Angular/Bootstrap Website!

I'm currently in the process of developing a website using Angular and Bootstrap for a non-profit organization that will facilitate donations through Paypal. On the platform, users will have the option to select their donation frequency (Weekly, Mont ...

Incorporating PruneCluster into an AngularJS Leaflet Directive for Enhanced Mapping

I am currently facing an issue with loading clustered markers for geojson data using PruneCluster. The clusters are not appearing on the map and there are no errors showing up in the console to assist with troubleshooting. Below is the snippet of my curr ...

What is the best way to make an exit pop up disappear when clicking on any area?

I'm new to programming in JavaScript and jQuery and I wanted to implement an exit pop-up feature. While I came across a helpful tutorial online, I encountered an issue where users could only exit by clicking on the "X" button. I want them to be able t ...

Is there a way to preserve the HTML template code as it is when saving it in a cell?

Looking to store an HTML email template in a Google Sheet cell, but running into formatting issues. The code resembles this example: See sample Email HTML code The problem arises when pasting the complete email template HTML code in a cell. Upon copying ...

Where can I find the link to access three.js on the internet?

Currently working on a JavaScript application within Google App Engine using three.js, but struggling to find the URL for online inclusion in my document. Uploading the entire large-sized three.js package is not ideal, so I'm looking for a way to obta ...

Angular only allows click events to trigger during a push

Is there a way to reveal the password without requiring a click, but simply by pushing on an eye icon? My code HTML <input [formControlName]="'password'" [type]="isShow ? 'text' : 'password'" class=&qu ...

Sending Grunt Jade configurations to a specific file

I'm currently using grunt-contrib-jade and I'm trying to utilize the pkg.name and pkg.version variables to generate my css file name. Unfortunately, I haven't been able to make this work on my own and would appreciate any assistance. Below i ...

I need to display the product name associated with the product_id found in the line_items array within the order table. I aim to achieve this functionality by utilizing Laravel with Vue.js

In my database, there is a cell called line_items in the orders table that contains data like: [ {"customer_id":"30","product_id":"10","unit_id":"2","quantity":"1","price":"2700","total_price":"2700"}, {"customer_id":"30","product_id":"43"," ...

Creating a seamless design with a navigation brand and login button on the same row within a navbar

I am trying to create a fixed navbar at the top of my webpage. The goal is to have the company's logo and name on the left side, with a log-in button on the right side. After reviewing multiple examples online, I found that most of them use a navbar- ...