Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .each() won't iterate independently

I'm using the following piece of jQuery to apply span styles to the currency symbol and decimals of a bunch of monetary values.

$('td.priceBox').each(function() {
    $(this).html('<span class="price_currency price_element">' + $(this).html().substr(0, 1) // this styles the currency unit
    + "</span>" + $(this).html().substr(1, $(this).html().length-3) // this leaves the rounded value as is
    + '<span class="price_cents price_element">'
    + $(this).html().substr(-2)
    + "</span>") // this styles the decimals
});

This code works for the first value on the page, e.g. "$180.65," but then copies that value and replaces every value on the page with "$180.65".

What am I doing wrong? How can I get this to iterate independently for each td.priceBox?

Note: The contents of td.priceBox are generated dynamically and I don't have access to them. I cannot write the spans inline.

EDIT: I had another script designed to remove the decimal $('.bannerContent td').html($('.bannerContent td').html().replace(".",""));. This targeted the same td, but didn't identify it by its class. This successfully removed the decimal, but for some reason it broke the .each() method. Why?

like image 808
brogrammer Avatar asked Dec 02 '25 06:12

brogrammer


1 Answers

$('.bannerContent td').html($('.bannerContent td').html().replace(".",""));

This code is replacing all the tds with the HTML of the first one. That's because while .html() as a setter function applies to the whole jQuery set, as a getter it only runs on the first. If you place this inside your .each() and use $(this) it should work:

$('td.priceBox').each(function() {
    $(this).html($(this).html().replace(".",""));
    $(this).html('<span class="price_currency price_element">' + $(this).html().substr(0, 1) // this styles the currency unit
    + "</span>" + $(this).html().substr(1, $(this).html().length-3) // this leaves the rounded value as is
    + '<span class="price_cents price_element">'
    + $(this).html().substr(-2)
    + "</span>") // this styles the decimals
});

For more information on how this works, see the jQuery .html() documentation.

like image 159
Scimonster Avatar answered Dec 03 '25 18:12

Scimonster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!