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