Formatting Numbers with a "class" and global JavaScript

I often find myself copying and pasting the same JavaScript on the bulk of my pages. Is it possible to have a global JavaScript function for a given “class” that can be put in Layout or the footer so I only have to enter the script once?

Examples would be formatting a number field from a pipe call or an equation field using the class “currency.” Or, using it to format form data using this code.

I tried every which way I could think of to rework the following JQuery so that it would work in either the Layout page or the custom footer section, but couldn’t figure it out.

@Chem is there something obvious I’m missing here?

Here is the base JQuery code, but it doesn’t seem to work for pipe calls in an HTML field, they just return $NaN:

$('.currency').each(function() {
    var item = $(this).text();
    var num = Number(item).toLocaleString('en');

    if (Number(item) < 0) {
        num = num.replace('-', '');
        $(this).addClass('negMoney');
    } else {
        $(this).addClass('enMoney');
    }
    $(this).text(num);
});

It works fine if I switch the first line to Tadabase flavor, but then I have to redo it for each component:

TB.render('component_XX', function(data) {
    data.ele.find('.currency').each(function() {
         // code goes here...
    });
});

I tried putting it in the Layout JavaScript section, switching the first line to match the main content component, but it did not work:

TB.render('component_layout_X', function(data) {

Just in case anyone wants to try it, it does work locally, but it’s quite tedious if you have several detail pages with a lot of numerical data piped in from other tables. You have to add a class of “currency” to whatever number you want to display as currency.

Here is the CSS:

.enMoney::before {
  content: "$";
}
.negMoney {
  color: red;
}
.negMoney::before {
  content: '($';
}
.negMoney::after {
  content: ')';
}

credit: here

2 Likes

create a table, store your codes in that table as records and reference the records as classes.

@james -

Is the reason why you are duplicating the CSS is due to the fact the end result is being “pipped” in by a numerical pipe? Thus, establishing CSS in the application settings Custom Header/Footer Code wouldn’t work.

Adam

@SafetyUniversity actually the CSS in the header/footer is fine. It’s the JS that needs to go on every page.

I think the reason this isnt working in the layout or custom footer is because the components on the page arent loading before the script runs.

There may be a work around for that but im not sure.

Hi James,

Howz the PWA coming along?

@james I wanted to point out that you can do component_any for any component and not have to specify each component ID.

1 Like