Reputation: 818
I have below 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 above code, I can create div dynamically for the input string array - Example: If I input [[8,2,5]], it creates three div with id's - 8,2,5
However, I would like to insert st value from the object named 'lookupdata' into the respective id div.
The purpose of this is, I want to use st as input to a chart within the inner div (with class 'st').
How can I do that?
Here is the working demo - http://jsfiddle.net/sathish_panduga/3581rh71/7/
Upvotes: 0
Views: 226
Reputation: 17795
You can use jQuery's grep function which is intended for searching 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 like this:
$( "<div id='sp"+array[i]+"'>This is div with id "+array[i]+getObjContents(Num)+"<div class='st'></div></div>" ).insertAfter( "#main");
Upvotes: 3