The complexity of adding an object as innerHTML to a dynamically created div in javascript / jquery

I have code in my project

HTML:

<input type="text" id="Num"> <input type="button" value="Insert Div" onClick="insertDiv(getElementById('Num').value)" /> <div class="container"> <div id="main">All starts from here</div> </div> 

JavaScript:

 lookupdata=[ {"id":2,"st":[{"label":"Audi","value":10},{"label":"BMW","value":70}]}, {"id":16,"st":[{"label":"Benz","value":40},{"label":"BMW","value":20}]}, {"id":8,"st":[{"label":"AUDI","value":60},{"label":"Tesla","value":70}]}, {"id":5,"st":[{"label":"MZ","value":30},{"label":"Honda","value":40}]} ]; function insertDiv(Num){ var ar1=Num.replace('[', ''); ar1=ar1.replace('[', ''); ar1=ar1.replace(']', ''); ar1=ar1.replace(']', ''); alert(ar1); var array = JSON.parse("[" + ar1 + "]"); alert(JSON.stringify(lookupdata,null,2)); var i=0; for(i;i<array.length;i++) { $( "<div id='sp"+array[i]+"'>This is div with id "+array[i]+"<div class='st'></div></div>" ).insertAfter( "#main"); } } 

Using the code above, I can dynamically create a div for an array of input strings - Example: if I enter [[8,2,5]], it creates three divs with id - 8,2,5

However, I would like to insert the st value from an object named 'lookupdata' into the corresponding id div.

For this, I want to use st as an input to the diagram inside the inner div (with the class 'st').

How can i do this?

Here is a working demo - http://jsfiddle.net/sathish_panduga/3581rh71/7/

0
javascript jquery
source share
1 answer

You can use the jQuery grep function designed to search for an array.

 function getObjContents(i){ var arr = $.grep(input, function(e){ return e.id == i; }); var str=""; for (var i = 0; i < arr[0].st.length; i++) { str += JSON.stringify(arr[0].st[i]); } return str; } 

You would call it this way:

 $( "<div id='sp"+array[i]+"'>This is div with id "+array[i]+getObjContents(Num)+"<div class='st'></div></div>" ).insertAfter( "#main"); 

Demo

+3
source share

All Articles