roy
roy

Reputation: 39

How to add dynamic lists in javascript not jquery

Am having the data as

var response = '[{"id":1,"name":"Web Demo"},{"id":2,"name":"Audio Countdown"},{"id":3,"name":"The Tab Key"},{"id":4,"name":"Music Sleep Timer"}]';
var obj = JSON.parse(response);

So how I can add the list items dynamically so in future if the list items in the backend increases they should be added directly and how can link dynamic and static elements.

Thanks

Upvotes: 0

Views: 5936

Answers (3)

Manjeet Barnala
Manjeet Barnala

Reputation: 2995

Use js appendChild to append each item in your html like this...

var response = [{"id":1,"name":"Web Demo"},{"id":2,"name":"Audio Countdown"},{"id":3,"name":"The Tab Key"},{"id":4,"name":"Music Sleep Timer"}] ;

for (i = 0; i < response.length; i++) 
{ 
	var node = document.createElement("LI");  // Create a <li> node
	var textnode = document.createTextNode(response[i].name); // Create a text node
	node.appendChild(textnode); 
	document.getElementById("items").appendChild(node); ///append Item
}	
<div id="items"></div>

Upvotes: 1

Charlie
Charlie

Reputation: 23778

If you want to change your lists according the the changes in the backend, you should periodically test for that via ajax. You can use setInterval and XMLHttpRequest for these purposes.

When the new data arrives, you should erase your existing list and add new elements to represent the arrived data dynamically.

setInterval(function(){

  var xhttp = new XMLHttpRequest();

  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {

     populateList(xhttp.responseText);   //This is your function to create the list

    }
  };

  xhttp.open("GET", "http://www.mybackend.com/list", true);
  xhttp.send();

})

And you can use document.createElement function to create a series of elements to represent your data.

function populateList(data) {

   var obj = var obj = JSON.parse(response);

   document.getElementById('myUl').remove();    //Delete the existing list

   var myUi = document.createElement('ul');    //Add new list

   obj.forEach(item) {

       var listItem = document.createElement('li');
       myUi.appendChild(li);

       //Then add li details here
   } 

}

This is just rough code. Your can youse Jquery to get this done very shorter than this. You can even use a JS framework like Angular to automate most of these tasks.

Upvotes: 1

Suresh
Suresh

Reputation: 923

If you are storing dynamic data as like static data, use concat

response.concat(dynamicdata);

Upvotes: 0

Related Questions