You are viewing limited content. For full access, please sign in.

Question

Question

Javascript:Field Formatting

asked on March 15, 2016 Show version history

Hello,

I have the following code & need some help.

The Class .subtotal should have ' as separator & should have 2 decimal points

The Class .total & .sub should have ' as separator 

$(document).ready(function () {

  
  
  $('.cf-table-block').on('blur', 'input', sumtotal);
	$('.tax').on('blur', 'input', sumtotal);
		function sumtotal() {
		var sum = 0;
        $('.cf-table-block tbody tr').filter(':visible').each(function () {

		var s = 0;
		s = parseNumber($(this).find('.price input').val()) * parseNumber($(this).find('.quantity input').val());
		$(this).find('.subtotal input').val(s);
		sum += s;
		
      });
		 $('.tax input').val((sum * 0.08).toFixed(2));
		 $('.sub input').val((sum).toFixed(2));
	   	$('.total input').val((parseNumber(sum) + parseNumber($('.tax input').val())).toFixed(2));
	}
  
  		function parseNumber(n) {
		var f = parseFloat(n); //Convert to float number.
		return isNaN(f) ? 0 : f; //treat invalid input as 0;
	}
  
  
});

I have tried various codes (from here) to achieve the result, but to no luck.

 

Please note the fields are of type = SingleLine

Thanks a lot in advance!

S

0 0

Answer

SELECTED ANSWER
replied on March 16, 2016 Show version history

Hi Sahil,

You can use JavaScript's ".replace()" method with regular expressions to achieve this. For every input field you want to format, give it a CSS class (I use ".regex" in the below example). Then try the the following JavaScript:

$('.regex input').each(function(){
  var reg = $(this).val();
  $(this).val(reg.replace(/\B(?=(?=\d*\.)(\d{3})+(?!\d))/g, "'"));
});

Let me know if this works for you!

0 0
replied on March 16, 2016

Perfect! 

0 0

Replies

You are not allowed to reply in this post.
You are not allowed to follow up in this post.

Sign in to reply to this post.