David Van Staden
David Van Staden

Reputation: 1789

jQuery appendTo function not working

Why is my function not working:

FIDDLE

HTML:

<div class="cash">1234.00</div>
<div class="cash">123456.00</div>
<div id="total"></div>

JS:

function formatPrice(price) {
    return price.reverse().replace(/((?:\d{2})\d)/g, '$1 ').reverse();
}

// Need to extend String prototype for convinience
String.prototype.reverse = function() {
    return this.split('').reverse().join('');
}

$('.cash').each(function(){
    $(this).html().formatPrice().appendTo('body');
});

I tried this as well, no luck:

$('.cash').each(function(){
    $(this).html() = i;
    formatPrice(i).appendTo('body');
});

Even whenstripping it down to a basic function, it still does not append my stuff...Am I losing my mojo?

$('.cash').each(function(){
    $(this).html().appendTo('body');
});

Thanks

UPDATE: The function is just suppose to do this:

formatPrice('1234.00') //convert to "1 234.00" formatPrice('123456.00') //convert to "123 456.00"

Upvotes: 1

Views: 10658

Answers (2)

Mikhail Chernykh
Mikhail Chernykh

Reputation: 2697

To make your example working, you should fix this part of code:

$('.cash').each(function(){
    $('body').append(formatPrice($(this).html()));
});

Here is Fiddle

You cannot run html().formatPrice(), because formatPrice() in your case is standalone function, but not a method of a string object.

If you want to replace the text inside div.cash, please use this code:

$('.cash').each(function(){
    $(this).html(formatPrice($(this).html()));
});

Here is the updated fiddle

If you want to be able to use formatPrice() for any string, please do the following:

String.prototype.formatPrice = function() {
    return this.reverse().replace(/((?:\d{2})\d)/g, '$1 ').reverse();
}

$('.cash').each(function(){
    $(this).html(function(i, h) { return h.formatPrice() });
});

Here is the Fiddle

So, just select the option you like and use it.

Upvotes: 7

fmsf
fmsf

Reputation: 37177

$(this).html() returns the html in text, not a jQuery object that contains the appendTo function.

You can do:

$($(this).html()).appendTo('body');

Btw you shouldn't "pick up html" and assume that it is safe to pass it to your formatPrice function.

Do like this, it is cleaner:

<div class="cash" data-cash="1234.00">1234.00</div>

$('body').append(formatPrice($(this).attr("data-cash")));

Upvotes: 4

Related Questions