Need help on client script to auto add comma and decimal (2 digits)

Bird1
Mega Sage

Hello,

 

I need help. I am creating a catalog item. There's a single line text variable I need to use to allow end-user to input the price.

 

So I am trying to create the client script. My goal is

 

- To ensure that only numeric value, comma, decimal are allow (no any other characters, $ and etc.)

- The on change client script should be able to add comma and decimal 2 digits (ie: if enter 1000, it will auto convert to 1,000.00)

- The 2 digits decimal should 'round up', so if enter 1000.556, it will auto convert to 1,000.56)

 

 

Here's my current script, it doesn't allow to enter decimal anymore but it could add comma already. Could anyone help? Thanks in advance.

 

function onChange(control, oldValue, newValue, isLoading, isTemplate) {

 

if (isLoading || newValue === '') {


return;


}


var result = formatNumber(newValue);


if (result == false) {


g_form.clearValue('price');
g_form.showFieldMsg('price', 'Only numeric values allowed', 'error');

 

return;

 

}


// To avoid recusrion


if (result != newValue) {


// Change u_field_name to the field on which this onChange script is applied


g_form.setValue('price', formatNumber(newValue));

 

}


}


function formatNumber(x) {


// Regular expression allowing only numeric values


var reg = /^[\d,]+$/;


if (!x.match(reg))


return false;


else


return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); // Insert commas at correct position


}

0 REPLIES 0