0

I have a list of cars:

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:

  • 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.

I'm trying to get my head around these requirements while I'm learning JS. I like to understand the thinking process about each step in order to learn correctly.

Taylan Aydinli
  • 4,333
  • 15
  • 39
  • 33
egyamado
  • 1,111
  • 4
  • 23
  • 44
  • 1
    So what have you tried so far? There is help on the web, e.g. [Traversing an HTML table with JavaScript and DOM Interfaces](https://developer.mozilla.org/en/docs/Traversing_an_HTML_table_with_JavaScript_and_DOM_Interfaces). I'm not endorsing the article, just pointing out that it may help. – RobG Nov 27 '13 at 06:22
  • @RobG, Thanks for your comment/help. As I mentioned I want to understand more the thinking process "explanation and meaning of requirements" more solving the task. For example, the last 2 req. are not clear to me, that's why I asked the question. – egyamado Nov 27 '13 at 06:32
  • 1
    Basically it sounds like you're looking for an html table for showing the types of cars. Each element in the table should be some clickable item that, when clicked, reveals the rest of the info on that vehicle. That's where I'd start - just analyzing the problem – Blundering Philosopher Nov 27 '13 at 06:34
  • About last one, how could that number be changeable/vary at any moment? – egyamado Nov 27 '13 at 06:50
  • That's where most of the javascript would come in most likely. You could have a few `` tags and a Submit ` – Blundering Philosopher Nov 27 '13 at 06:56

1 Answers1

1

Here is an example that may solve your requirements:

1) As I mentioned in a comment, There is an html table with three columns.

2) Sorts cars by model name.

3) When the models are clicked, additional information is displayed about the car. (in this case, in an alert window)

4) You can add cars to the list with the form, and the table is then regenerated.

Run code here.

<html>
  <head>
    <title>Just for fun</title>
  </head>
  <body>
    <h3>Cars and types:</h3>
    <form name="myForm" onsubmit="return mysubmit()">
      Model: <input type="text" name="model"><br>
      Count: <input type="text" name="count"><br>
      Details: <input type="text" name="details"><br>
      <input type="submit" value="Submit">
    </form>
    <button onclick="generate_table()">Generate Table</button><br>
    <table class="cars">
    </table>
    <div class="details" style="float:right;">
    </div>
    <script>
      console.log('script started');
      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>"}
      ]

      var types = ["model","count","details"];

      function generate_table() {
          cars.sort(compare);
          var body = document.getElementsByTagName("body")[0];

          // creates a <table> element and a <tbody> element
          var tbl     = document.getElementsByClassName("cars")[0];
          tbl.innerHTML = '';
          var tblBody = document.createElement("tbody");
          console.log(cars.length);
          for (var i = 0; i < 3; i++) {
              var index = ((j*3)+i);
              if (index < cars.length) {
                  // Create a <td> element and a text node, make the text
                  // node the contents of the <td>, and put the <td> at
                  // the end of the table row
                  var cell = document.createElement("td");
                  var num = index;
                  cell.innerHTML = '<a href="#" onclick="showDetailsAsDiv('+num.toString()+')">' + cars[index][types[0]] + '</a> (' + cars[index][types[1]] + ')';
                  row.appendChild(cell);
              }
          }
          tbl.appendChild(tblBody);
          body.appendChild(tbl);
          tbl.setAttribute("border", "2");
      }

      // This function throws details into 'details' div
      function showDetails(num) {
          console.log('details showing',num);
          div = document.getElementsByClassName('details')[0];
          div.innerHTML = '';
          var car = cars[num];
          div.innerHTML = 'Model: ' + car.model + '</br>Count: ' + car.count +
              '</br>Details:\t' + car.details;
      }

      function mysubmit() {
          var model = document.forms["myForm"]["model"].value
          var count = document.forms["myForm"]["count"].value
          var details = document.forms["myForm"]["details"].value

          cars.push({
              model:model,
              count:count,
              details:details
          });
          generate_table();
          return false;
      }

      function compare(a,b) {
        if (a.model < b.model)
           return -1;
        if (a.model > b.model)
          return 1;
        return 0;
      }
    </script>
  </body>
</html>

EDIT: Changed code to throw details into div instead of alert box - this way you can see the HTML being run.

EDIT2: Shows cars in 3 columns.

References:

Sorting Function

generate_table function [slightly modified]

Community
  • 1
  • 1
Blundering Philosopher
  • 6,245
  • 2
  • 43
  • 59
  • After RobG's comments & yours, I start work on the HTML side and I almost get here http://fiddle.jshell.net/uwUEL/, and still searching how to loop through an Array. And I thought to share with you before I know u submitted a solution. :) I'll give it a try, Thanks – egyamado Nov 27 '13 at 08:54
  • I have tried your solution and it works. Instead of showing alert message which it shows HTML element as raw view, I want it to show it as HTML. What is good way to do so, show the content as html, or save these info in HTML file and show that specific section "content" that related to each model? It sounds complicated; Hope I'm clear. – egyamado Nov 27 '13 at 15:32
  • The way table structures is good, I'm trying to display only the model as link and count as text like so: "BMW(12)", so when you click on that link it shows content as html. – egyamado Nov 27 '13 at 15:55
  • 1
    1) Cool, it looks like you understand how to loop through an Array now, right? 2) There's a few ways to show the HTML content. One way is to create a popup window, which requires jQuery and a decent amount of code. Another is just link to another page, which I can demonstrate. 3) How many columns do you want the table to show? Just one with the model and count? [example: column showing "BMW(12)"] – Blundering Philosopher Nov 27 '13 at 18:23
  • Also, for (2) - displaying the HTML details - you can just have an empty `
    ` element that, when a link is clicked, fills with the car details. Which solution would be best for you?
    – Blundering Philosopher Nov 27 '13 at 18:30
  • I had tried to do it using jQuery, but I got stuck on displaying part of HTML page represent "details. here http://jsfiddle.net/vRPUT/1/ . Also I'm trying to show list of cars like so http://postimg.org/image/jlxz8fwun/, I think it should be done by looping against model and count and incerment that, right? – egyamado Nov 27 '13 at 20:01
  • I like to know both ways to display HTML "details". Can we use pure JS with jQuery as well? – egyamado Nov 27 '13 at 20:05
  • 1
    First, I thought it would be helpful just to get the table looking like you want it. Look at this last edit [i changed the link] which hopefully makes the table look closer to what you want - It isn't formatted beautifully, but functionally it looks the same. – Blundering Philosopher Nov 27 '13 at 20:44
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/42072/discussion-between-egyamado-and-maniacal-monkey) – egyamado Nov 27 '13 at 21:27