0

I have an array of objects. Each object contain few parameters. What I am trying to do is to run over the array and get from each cell the data and present it on a tabel/grid.

Example code

function addButton(){
    var phoneNumber = document.getElementById("phoneNumber").value;
    var email = document.getElementById("email").value;
    var typeNotification = document.getElementById("typeNotification").value;
    var valueNumber = document.getElementById("valueNumber").value;
    var delayLimit = document.getElementById("delayLimit").value;
    var timeStart = document.getElementById("timeStart").value;
    var timeEnd = document.getElementById("timeEnd").value;

    var notify = {
        typeNotification : typeNotification,
        email : email,
        delayLimit : delayLimit,
        timeStart : timeStart,
        timeEnd : timeEnd,
        valueNumber : valueNumber,
        phoneNumber : phoneNumber
    };

    var notificationList = [];
    notificationList.push(notify);
    console.log(notificationList);

    var notificationListLength = notificationList.length;
    for(var i = 0;i < notificationListLength;i++){
        <div class="container">
            <div class="row">
                <div class="col">
                    1 of 2
                </div>
                <div class="col">
                    2 of 2
                </div>
            </div>
            <div class="row">
                <div class="col">
                    1 of 3
                </div>
                <div class="col">
                    2 of 3
                </div>
                <div class="col">
                    3 of 3
                </div>
            </div>
        </div>
    }
}

Inside the loop it gives me error with the Tags.

As you can see, when the user press the AddButton it gets all the data and restore it in object, then I add the object into Array, and then I run on the array and get from each cell of the array the data and I want to show it in Grid. Like I said it gives me error inside the loop with the tags.

Any idea how can I solve it?

4
  • 1
    You can't just insert HTML tags into a JS loop. If you want to add HTML to the DOM, look into DOM methods. Commented Jul 7, 2018 at 10:26
  • wow thats alot to read, and im also new in Javascript. can you please point me how can i resolve that? how should i do that? Commented Jul 7, 2018 at 10:31
  • Take a look at these questions and see if the answers in them help at all: stackoverflow.com/questions/18703780/… and stackoverflow.com/questions/29621860/… Commented Jul 7, 2018 at 10:33
  • 1
    You are going in complete wrong way you should start learn java script from basic. Commented Jul 7, 2018 at 10:34

2 Answers 2

3

You need to build up the output of html/tags you want, then add that to a targeted element on the page, like so:

<div id="target"></div>

<button onclick="addButton()">Add</button>

<script>
    const
        target = document.querySelector('#target'),
        notificationList = [{
            typeNotification: 'typeNotification',
            email: 'email',
            delayLimit: 'delayLimit',
            timeStart: 'timeStart',
            timeEnd: 'timeEnd',
            valueNumber: 'valueNumber',
            phoneNumber: 'phoneNumber'
        }];

    let output = '';

    function addButton() {
        notificationList.forEach(item => {
            output = `
            <div class="container">
                <div class="row">
                    <div class="col">
                        ${item.email} - 1 of 2
                    </div>
                    <div class="col">
                        ${item.typeNotification} - 2 of 2
                    </div>
                </div>

                <div class="row">
                    <div class="col">
                        ${item.timeStart} - 1 of 3
                    </div>
                    <div class="col">
                        ${item.timeEnd} - 2 of 3
                    </div>
                    <div class="col">
                        ${item.delayLimit} - 3 of 3
                    </div>
                </div>
            </div>
        `;
            target.innerHTML += output
        });
    }
</script>

As you can see, you can adjust the output before you add it to the target.

I have made all the properties in notificationList strings to save time, but in your example, they would be made up of other elements on the page.

Here is a working example: https://jsfiddle.net/14o8n30u/6/

--EDIT--

Here is the same thing, but this time a table gets updated, using javascript builtin table functions:

<button onclick="addButton()">Add</button>
<table></table>

<script>
    const
        targetTable = document.querySelector('table'),
        headerRow = targetTable.createTHead().insertRow(),
        tableBody = targetTable.createTBody(),
        notificationList = [];

    headerRow.insertCell().textContent = 'Notification Type';
    headerRow.insertCell().textContent = 'Email';
    headerRow.insertCell().textContent = 'Delay Limit';

    function addButton() {
        while (tableBody.firstChild) {
            tableBody.removeChild(tableBody.firstChild);
        }

        notificationList.push({
            typeNotification: `Type${Math.floor(Math.random() * Math.floor(10))}`,
            email: `Name${Math.floor(Math.random() * Math.floor(1000))}@test.com`,
            delayLimit: `${Math.floor(Math.random() * Math.floor(100))} seconds`,
        });

        notificationList.forEach(item => {
            const newRow = tableBody.insertRow(0);

            newRow.insertCell().textContent = item.typeNotification;
            newRow.insertCell().textContent = item.email;
            newRow.insertCell().textContent = item.delayLimit;
        });
    }
</script>

On mine, I used random data for illustration purposes, but in yours the data will be built from elements on the page.

Note that you have to keep the notificationList outside the addButton, or it gets reset to an empty array each time the button is clicked.

When the page loads, the table head and body are populated.

Then when the addButton is clicked, the table body is emptied, then a new notification is added to the notificationList.

Then, inside the forEach, which loops over the notifications, all the notifications get their own row added at the top of the table (i.e. the entire table body is repopulated each time addButton is clicked).

You may not need to populate your own table header, but if you do, you can see how in this example.

Here it is working (I couldn't get it to work on jsfiddle for some reason): https://codepen.io/leonsegal/pen/oyKBQb

Hope that helps

Sign up to request clarification or add additional context in comments.

1 Comment

It works! but its just print it each data in a new line, it ignores the table
0
   var notificationListLength = notificationList.length;
   var html_data = '';

    for(var i = 0;i < notificationListLength;i++)
    {
       html_data += '<div class="container">
                        <div class="row">
                          <div class="col">
                            1 of 2
                         </div>
                         <div class="col">
                           2 of 2
                         </div>
                      </div>

                     <div class="row">
                      <div class="col">
                       1 of 3
                      </div>
                      <div class="col">
                       2 of 3
                      </div>
                      <div class="col">
                       3 of 3
                      </div>
                    </div>
                  </div>';
         }
  /* Make a div(id="html_div") when you need display data */
  document.getElementById("html_div").innerHTML  = html_data ; 

2 Comments

So inside the colums i can add lables and with the document.getElementById i can add the data from the array object?
try to use something like:- <label>'+ notificationListLength[i] +'</label>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.