3

Is it possible to achieve this in javascript?

Here is the format:

1 ITEM1      9.00   0%  9.00
1 ITEM-GET01 8.00   12% 5.00

I would like to create a receipt like layout. I'm using backbone.js so there will be models and collection involve.

Also if it were on a table can I use jquery to get the data from the table tr then have the result just like what is posted above?

I was able to read about sprintf but I don't think it it is the one I need. any ideas?

UPDATE

I'm trying out sprintf here is what i've come so far

var result = sprintf("%d %-s %.2f %d%% %.2f", model.get("Qty"), model.get("Itemname"), model.get("Price"), model.get("Discount"), model.get("ExtPrice"));

result is:

1 Item1 1.49 0% 1.49
n0minal
  • 3,155
  • 9
  • 43
  • 71
  • 3
    Do you mean how to manipulate HTML using javascript to get this structure ? – Diode Aug 17 '12 at 09:06
  • Using sprintf-like formatting strings won't help you if you are not using a monospace font. – Imp Aug 17 '12 at 09:12
  • @Diode its a yes and a no. What i'm doing is manipulating the strings but if it would be easier and doable on html then yes. – n0minal Aug 17 '12 at 09:22
  • What's the input/output? What do you have and what do you want to get? Is it a table or a string with whitespace? – pimvdb Aug 17 '12 at 09:22
  • @pimvdb input would be data from backbone model more likely json format. i would like to be able to console.log the result in the format i've posted above. is it possible? – n0minal Aug 17 '12 at 09:24
  • That can be achieved using html,jquery and css. – Gandalf Aug 17 '12 at 09:27
  • possible duplicate of [JavaScript equivalent to printf/string.format](http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format) – Peter O. Mar 15 '13 at 13:00

2 Answers2

1

Read this article to use javascript similary sprintf in C...

http://www.webtoolkit.info/javascript-sprintf.html

or better read: JavaScript equivalent to printf/string.format

Community
  • 1
  • 1
Snake Eyes
  • 15,519
  • 32
  • 105
  • 203
  • Apparently, the OP already has a working `sprintf` function. The question is how to do indenting for a table, if I'm understanding it correctly. – pimvdb Aug 17 '12 at 09:35
0

You can do this in different ways. The method usually used is to loop in the data array and add rows in a table in which width of each column is set. Please see the sample in jQuery

var data = [
    {
    no: 1,
    name: "ITEM1",
    price1: "9.00",
    perc: "0%",
    price2: "9.00"},
{
    no: 2,
    name: "ITEM-GET01",
    price1: "9.00",
    perc: "12%",
    price2: "5.00"}
];

//$("#list tr").remove();    
$(data).each(function(index, item) {
    $("#list").append('<tr><td width="50">' + item.no + '</td><td width="100">' + item.name + '</td><td width="100">' + item.price1 + '</td>' + item.perc + '<td width="100">' + item.price2 + '</td></tr>');
})

demo : http://jsfiddle.net/diode/E8a6V/

Diode
  • 23,400
  • 8
  • 39
  • 50