1

I am new in jQuery, and can't seem to get the following code to work to my liking:

<script type="text/javascript">
        jQuery(document).ready(function($) {
            $.fn.digits = function(text){
                $(this).text(text.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") + '€' );
            };
            var tempText = $.trim($("#price").text());
            tempText = tempText.substr(0, parseInt(tempText.length) );
            $("#price").digits(tempText);
        });
</script>

It's should convert numbers in all #price divs into comma seperated currency versions:

1000000 = 1,000,000€

This works fine for the fist instance of #price on a page, but if the same ID appears more than one time on the same page, the rest are not being formatted by the script.

I found out that DIV's mus be unique, so i tried to change then to classes in stead (#price to .price) which does the trick, but now creates a new problem. Now all instances of the .price are shown in every instance of the .price - if that makes sense.

Let's say i have .price 3 times in one page:

Example 1 (.price): 200000

Example 2 (.price): 250000

Example 3 (.price): 300000

Should show:

200,000€

250,000€

300,000€

In stead it gives me:

200,000€ 250,000€ 300,000€

200,000€ 250,000€ 300,000€

200,000€ 250,000€ 300,000€

Why is that, and how do i fix it?

Thanks!

emiliano85
  • 129
  • 10

1 Answers1

0

if you want to affect multiple elements use class referencing rather than divs.

change this line

$("#price").digits(tempText);

to

$(".price").digits(tempText);

since classes are used for collection of elements and divs are used to reference only one item at a time... so it fetches the first div only.

and remember when using $('.price') you have to use a loop rather.. since they are many of them.. so your code becomes

$.each('.price', function(o, v){
   var tempText = $.trim($(this).text());
   tempText = tempText.substr(0, parseInt(tempText.length) );
   $(this).digits(tempText);
});

all things being equal, this should work...

Ande Caleb
  • 1,163
  • 1
  • 14
  • 35