brogrammer
brogrammer

Reputation: 864

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?

Upvotes: 3

Views: 108

Answers (2)

Scimonster
Scimonster

Reputation: 33399

$('.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.

Upvotes: 4

Twan Haverkamp
Twan Haverkamp

Reputation: 31

I think this also should work:

$('td.priceBox').each(function() {
var content       = $(this).html(),
    span          = $('<span />'),
    span_currency = span.addClass('price_currency price_element').html(content.substr(0, 1)),
    span_cents    = span.addClass('price_cents price_element').html(content.substr(-2));

    // Remove current content
    $(this).empty();

    // Add currency
    $(this).append(span_currency);

    // Add rounded value
    $(this).append(content.substr(1, (content.length - 3)));

    // Add cents
    $(this).append(span_cents);

});

Upvotes: 3

Related Questions