-1

I am hearing so much about populating a table. When I look it up at google there is a whole universe of post how to do that. But let's talk about populating a view!
Yes, you heard right! I think it's such as the simplest and most normal way everybody would do the first time.

I want to create a list! In this simple list, I want to show sentences. Something looks like this: https://www.dropbox.com/s/swm1n9ezled0ppd/img.jpg?dl=0
And my idea was it to use for every single item a div, with a title in it and so on. But how would I populate that div with help of javascript? And the most important thing how to set the titles of the divs to a different value?

How to do that via JavaScript or is there another much better way i did not know?

EDIT:

db.collection("classes").doc(data.readGrades).get().then(function(doc) {
      if (doc.exists) {
        console.log("Document data:", doc.data());
        const data = doc.data();
        const members = data.members;
        var permission_table = document.getElementById("noten_tabelle_permission");
        var permission_table_container = document.getElementById("main_padding");

        members.forEach(el => {
          console.log(el)

          table_number++;

          clone = permission_table.cloneNode(true); // true means clone all childNodes and all event handlers
          clone.id = "layout_table" + table_number;
          permission_table_container.appendChild(clone);

          db.collection("users").doc(el).collection("grades").get().then(function(querySnapshot) {
            querySnapshot.forEach(function(doc) {
                console.log(doc.id, " => ", doc.data());
                const data = doc.data();
                //addToTable("grade_table" + table_number, doc.id, data.mdl, data.klu);
                //window.alert("Table name: " + ["grade_table" + table_number])
                //____________________________________________________________________________

                const html = fillTemplate("grade_table" + table_number, "test", data.mdl, data.klu);

                // Join the array of html and add it as the `innerHTML` of `main`
                document.getElementById("main_padding").insertAdjacentHTML('beforeend', html);

                addToTable("grade_table" + table_number, doc.id, data.mdl, data.klu);

            });
          });
        })

      } else {
        console.log("No such document!");
      }
    }).catch(function(error) {
      console.log("Error getting document:", error);
    });

here is your writte function edited:

function fillTemplate({ table_name, id, subject, mdl, klu }) {
  return `
  <div class="noten_tabelle_permission" id="noten_tabelle_permission">
    <h1 id="member_name">${id}</h1>
    <table id="${table_name}" style="width:100%">
      <tr>
        <th>Fach</th>
        <th>mündlich</th>
        <th>Klausur</th>
      </tr>
      <!-- Make content with js code -->
    </table>
  </div>
  `;
}  

And here the other function:

function addToTable(table_name, subject, mdl, klu) {

  var subject_name = getSubjectByNumber(subject);
  var short_subject = getSubjectShortByNumber(subject);

      //Zeile erstellen

      var y = document.createElement([short_subject]);
      y.setAttribute("id", [short_subject]);
      document.getElementById([table_name]).appendChild(y);

      //Spalten in einer Zeile

      var y = document.createElement("TR");
      y.setAttribute("id", [short_subject]);

      //Spalten in einer Zeile

      var cE = document.createElement("TD");
      var tE = document.createTextNode([subject_name]);
      cE.appendChild(tE);
      y.appendChild(cE);

      var a = document.createElement("TD");
      var b = document.createTextNode([mdl]);
      a.appendChild(b);
      y.appendChild(a);

      var c = document.createElement("TD");
      var d = document.createTextNode([klu]);
      c.appendChild(d);
      y.appendChild(c);


      document.getElementById(table_name).appendChild(y);
}  

And here the HTML:

<div class='main_has_permission' id="main_has_permission" style="display: none;">
            <div class='main_padding' id="main_padding">

              <div class="noten_tabelle_permission" id="noten_tabelle_permission">
                <h1 id="member_name"></h1>
                <table id="grades_table" style="width:100%">
                  <tr>
                    <th>Fach</th>
                    <th>mündlich</th>
                    <th>Klausur</th>
                  </tr>
                  <!-- Make content with js code -->
                </table>
              </div>
            </div>
          </div>

Thanks in advance. ~carl

Carl Matig
  • 11
  • 3
  • 2
    This question is too broad for SO. Where is the data for the list coming from? Do you know any HTML, CSS, JS? Are you asking us to do the work for you? Because a list is very easy to create _without_ JS but you've not even shown us how you might approach _that_. (see [mcve]). – Andy Jan 11 '19 at 19:17
  • @Andy Can you look at my edit, please? – Carl Matig Jan 11 '19 at 19:42
  • Here's what we need to know to be able to help: 1) where is your data coming from? 2) Are you using any specific tools (such as javascript frameworks, web development frameworks, etc) 3) What do you already know about javascript, (what have you tried, where have you started from?) ... – Garrett Motzner Jan 11 '19 at 19:59
  • This may help: https://www.w3schools.com/howto/howto_js_todolist.asp – Garrett Motzner Jan 11 '19 at 20:06
  • And also take look at this question: https://stackoverflow.com/questions/11128700/create-a-ul-and-fill-it-based-on-a-passed-array – Garrett Motzner Jan 11 '19 at 20:06
  • @GarrettMotzner Let us take simple sentences or words which are in a arraylist# – Carl Matig Jan 11 '19 at 21:00

1 Answers1

1

OK, so I was a little bored :) so I cooked up an example to help you out. It contains:

1) An array of objects containing your data. Each object has a title, an array of genres, and a year.

2) It uses map to iterate over the data array and call fillTemplate for each object.

3) fillTemplate returns a completed template literal using each array object's data. Note: because genre is an array of genres we use join to join the array elements together into a list.

4) It uses the CSS flex model to style the HTML.

const data = [{ title: 'Mad Max: Fury Road', genre: ['Action & Adventure'], year: 2015 }, { title: 'Inside Out', genre: ['Animation', 'Kids & Family'], year: 2015 }, { title: 'Star Wars: Episode VII - The Force Awakens', genre: ['Action'], year: 2015 }];

function fillTemplate({ title, genre, year }) {
  return `
    <section class="panel">
      <div class="left">
        <div class="title">${title}</div>
        <ul class="genres">
          <li class="genre">${genre.join('</li><li class="genre">')}</li>
        </ul>
      </div>
      <div class="year">${year}</div>
    </section>
  `;
}

// For each array object call `fillTemplate` which returns a new
// array element of HTML 
const html = data.map(obj => fillTemplate(obj));

// Join the array of html and add it as the `innerHTML` of `main`
document.querySelector('main').innerHTML = html.join('');
main { display: flex; flex-direction: column; }
.panel { width: 60%; display: flex; padding: 0.5em; margin: 0.2em 0 0.2em 0; border: 1px solid #565656; background-color: #efefef; flex-direction: row; align-items: flex-start; }
.genres { margin: 0.3em 0 0 0; padding-left: 0; list-style-type: none; }
.panel div:first-child { width: 100%; }
.genre { display: inline-flex; margin-right: 0.4em; }
.title { font-weight: 600; font-size: 1.1em; }
.year { text-align: right; }
<main></main>

JSFiddle

Andy
  • 61,948
  • 13
  • 68
  • 95
  • Thanks for understanding my Problem. Thanks for your help. Please have a look at my EDIT. I modified your code, but I get an error. Why? As you can see I take the data from firebase and want to create for every "data pack" an own table. So I want to populate the table with your function and than add the rest to the populated table with my function "addToTable". What I am doing wrong and how to fix it? – Carl Matig Jan 11 '19 at 22:10
  • Try `document.getElementById("main_padding").insertAdjacentHTML('beforeend', html);`. You're not creating a new array so joining one makes no sense. Here's the documentation for [insertAdjacentHTML](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML). – Andy Jan 11 '19 at 22:19
  • Ok thanks, Andy. The error disappeared. Can you please have a look at my again and help me out of the last issues I have? The problem is, that I don't know if a table is really created or the code doesn't find him. Because now I am getting this error: `Cannot read property 'appendChild' of null` for this line: `document.getElementById([table_name]).appendChild(y);`. – Carl Matig Jan 12 '19 at 20:30
  • I'm not sure why you're adding `table_name` as the first element of an array. If `table_name` exists as an ID in your HTML, just do `document.getElementById(table_name)`. And make sure that you do that for all those other instances. `document.createElement([short_subject]);` should be `document.createElement(short_subject);` assuming that `short_subject` is an element name like `DIV` or `IMG`. – Andy Jan 12 '19 at 21:38
  • Please have a look at my added Code in Edit. So that's exactly the point... I want to make a list view of tables. And I don't know how much tables I need. So I must create the tables by js. And then add values to them. But anything doesn't work in this code. – Carl Matig Jan 15 '19 at 07:17