2

Trying to append array values to divs, this part works , nothing wrong here, but i need the array values to be formatted and it would be simple and neat to just pass the value through a function right before the appendTo() jquery function, dont know if this is possible though...

have a long list of this: $(c[3]).appendTo('#output_div_id1');

what im trying to achieve is $( number_format(c[3])).appendTo('#div');

This does not seem to be working. Ideas how i could achieve this?

JazzCat
  • 4,243
  • 1
  • 26
  • 40

3 Answers3

0

You can format the entries before you append them

OR

You can try modifying the jQuery prototype:

$.fn.numberFormat = function () {
    var htmlStr = $(this).html();

    //do stuff to the html (or whatever you're changing)

    return $(this).html(htmlStr);
};

and then use it like:

$(c[3]).numberFormat().appendTo('#div");
mahercbeaucoup
  • 597
  • 5
  • 15
  • Yeah i tried formatting them through a for loop for(var i = 3; i < c.length; i++) { c[i] = number_format(c[i],0, ',', ','); } but for some reason that didnt work.. – JazzCat Nov 02 '12 at 14:15
0

Or just use append(). http://api.jquery.com/append/

Example:

<div id="element">Hello</div>
$('#element').append(function(index, html) {
    return ' world!';
});
Cravid
  • 653
  • 2
  • 7
  • 22
  • this won't work - it appends the result of the function to every element matching the given selector, and *not* the contents of his array. – Alnitak Nov 02 '12 at 14:05
  • Thats kind of what i wanted :) dont have to change the array just output the correct numbers, why didnt i think of this? :) thanks buddy – JazzCat Nov 02 '12 at 14:22
  • @idontgetdottynetty that's not my point - there's nothing in this answer that handles adding your original array to `#element` one element at a time. – Alnitak Nov 02 '12 at 14:29
0

Given an array a, and a transmutation function f, the code below will append each element of the array to the given selector having passed it through that function:

$.fn.append.apply($('#div'), $.map(a, f));

so, in your case given:

function number_format(n) {
    return n.toFixed(2);  // modify to suit
}

you would use:

$.fn.append.apply($('#div'), $.map(c, number_format));

and the result will be that every element of c will be passed to number_format and then appended to the div, leaving the original array untouched.

Alnitak
  • 334,560
  • 70
  • 407
  • 495