0

I have the following variable:

  var cars = [
      {model: "BMW", count: 23, details: "<p>I like <b>X6</b> from Germany</p>"},
      {model: "Hyundai", count: 30, details: "<p>I have <b>Verna</b> from Korea</p>"},
      {model: "Toyota", count: 08, details: "<p>Small <b>Yaris</b> from Japan</p>"},
      {model: "Fiat", count: 12, details: "<p>Latest <b>500c</b> from Italy</p>"}
  ]

What I'm trying to do is, create a table with only 3 columns, that display only Model and count like so 'BMW(23)', then when I click on 'BMW' only it opens an HTML page which shows 'details'.

I have looked at How do I create HTML table using jQuery dynamically? but I'm not able to achive the requrienment:

  • The list should always be displayed in a three column layout, also in the case of, for instance, only four models in total.
  • List should be ordered alphabetically.
  • Clicking on each car, model should display additional information about the car (some html) as listed above.
  • The number of cars in the list can vary at any moment.

Thanks...

Community
  • 1
  • 1
egyamado
  • 1,111
  • 4
  • 23
  • 44
  • 2
    You're asking quite a bit, sorting the array, creating the HTML, making it open a new page etc. and it doesn't look like you've tried anything yourself. This is not a place where we write your code for you, it's a place where you can get help once you're stuck with an actual problem. – adeneo Nov 27 '13 at 16:16
  • @adeneo, I have tried in JS only but it's working as it should. Also I found creating table with DOM in JS could confuse you. I want to know if there is more simpler way.I'm stuck at this point. – egyamado Nov 27 '13 at 16:20

1 Answers1

2

This should get you started

jsfiddle demo

// sort the cars alphabetically by model
cars.sort(function(a, b) { return a.model > b.model; });

// create table
var table = $("<table></table>");

$.each(cars, function(idx, car) {

  var row = $("<tr></tr>");

  row.append($("<td></td>").html(car.model));
  row.append($("<td></td>").html(car.count));
  row.append($("<td></td>").html(car.details));

  table.append(row);
});

// insert the table somewhere in your dom
$(document.body).append(table);

Edit: I was originally using .text to set the content of the TD elements. However, because you have HTML in your data object, I used .html to set the table cell contents.

maček
  • 76,434
  • 37
  • 167
  • 198