Is it possible to auto create a table from json files based on selected values.
$(document).ready(function(){
$("#dropdown_change").change(function(){
alert("Selected value is : " + document.getElementById("dropdown_change").value);
});
With your given json i'hv made an example. Look into this.
$("#dropdown_change").change(function() {
var val = $(this).val();
alert("Selected value is : " + val);
var projects = PROJECTDETAILS.filter(function(pd) {
return pd['Project key'] == val;
})
if (projects.length) {
var html = '';
projects.map(function(pro) {
html += '<tr>';
for (var i in pro) {
html += '<td>' + pro[i] + '</td>';
}
html += '</tr>';
})
$('table').find('tr').not(':eq(0)').remove();
$('table').show().append(html);
}
});
var PROJECTDETAILS = [{
"Project key": "Bluesky",
"Employee Name": "anusha",
"Issue Id": "0011",
"Charge No": "1111",
"Hours": "10"
}, {
"Project key": "Bluesky",
"Employee Name": "anusha",
"Issue Id": "00123",
"Charge No": "1111",
"Hours": "10"
}, {
"Project key": "project2",
"Employee Name": "kavya",
"Issue Id": "00452",
"Charge No": "1111",
"Hours": "10"
}]
$(document).ready(function() {
$("#dropdown_change").change(function() {
var val = $(this).val();
alert("Selected value is : " + val);
var projects = PROJECTDETAILS.filter(function(pd) {
return pd['Project key'] == val;
})
if(projects.length){
var html = '';
projects.map(function(pro){
html+='<tr>';
for(var i in pro){
html+='<td>'+pro[i]+'</td>';
}
html+='</tr>';
})
$('table').find('tr').not(':eq(0)').remove();
$('table').show().append(html);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown_change">
<option value="Bluesky">Bluesky</option>
<option value="project2">project2</option>
</select>
<table style="display: none">
<tr><th>Project key</th><th>Employee Name</th><th>Issue Id</th><th>Charge No</th><th>Hours</th></tr>
</table>
Related
I want to make a dropdown in my table which is populated with the dynamic data coming from ajax response and append to the table.
My postman collection looks like this.
{
"createdDate": "2022-04-06T11:42:37.360Z",
"enabled": true,
"_id": "62502b868daa3b1cdbdc98e8",
"CNIC": "40740c7d9f3a11d93e76af7f2f60887a",
"employeeID": "LE44337",
"fName": "HUSNAIN",
"company": "6249fdf91399dc7a14173dcd",
"fatherName": "husnain",
"motherName": "momutaz",
"spouse": "no spouse",
"children": [{
"_id": "62502b868daa3b1cdbdc98e9",
"name": "hunsian",
"age": 23232
}, {
"_id": "62502b868daa3b1cdbdc98ea",
"name": "hunsian",
"age": 12121
}, {
"_id": "62502b868daa3b1cdbdc98eb",
"name": "momin",
"age": 2323
}
}
And below is my ajax response code in which I am appending the data into table.
success : function(response){
var trHTML = '';
$.each(response.doc, function (i, item) {
trHTML += '<tr><td>' + item.fName + '</td><td>' + item.CNIC + '</td><td>' + item.spouse + '</td><td>'+ item.fatherName + '</td><td>' + item.motherName +'</td><td>'+ item.employeeID +'</td><td>' + item.children.map(({name, age}) => `Name: ${name} Age: ${age}`).join(' || ') +'</td></tr>';
});
$('#records_table').append(trHTML);
}
The itme.children name , age I want to make a dropdown of it into table so it looks good.
If you mean a dropdown like a select menú, this should do the job
trHTML += `... <td>
<select>
<option selected disabled>Click me</option>` +
item.children.map(({name + age}) => `<option>Name: ${name}, Age: ${age}</option>`).join('') +
`</select></td>`;
I made a page like this with json. I added my test example the link at the bottom of the article. I listed the categories in this way with json. But there is something else I want. After selecting the category, I want to show the subcategories of the selected category on the screen, on the same page, maybe in the same area. How can I do this?
these are the codes I added as an example. You can see the site I prepared at the bottom of the article.
So actually when the category is selected, I want to show subcategory on the screen.
HTML
<ul id="category" class="grid">
</ul>
JAVASCRİPT
$(function() {
var people = [];
$.getJSON("category.json", function (data) {
$.each(data.cat_en, function(i, f) {
var tblRow = '<li class="grid_item">' + ''+ '<div>'+'<div>'+'</img>'+'</div>'+ '<div>'+ f.cat_name + '<span>'+ f.cat_product_count +'</span>' + '</div>'+ '</div>'+''+'</li>'
$(tblRow).appendTo("#category")
})
})
})
JSON
{
"cat_en" :
[
{
"cat_name": "Aluminum Components",
"cat_url": "#",
"cat_product_count": 29
},
{
"cat_name": "Gas Springs",
"cat_url": "#",
"cat_product_count": 75
},
{
"cat_name": "Lighting Parts",
"cat_url": "#",
"cat_product_count": 271
},
{
"cat_name": "Rear View Mirrors And Components",
"cat_url": "#",
"cat_product_count": 71
},
{
"cat_name": "Freezer And Components",
"cat_url": "#",
"cat_product_count": 22
},
{
"cat_name": "Upholstery fabrics",
"cat_url": "#",
"cat_product_count": 13
}
]
}
demo site
If we assume subcategories stored in each object,
{
"cat_name": "Aluminum Components",
"cat_url": "#",
"cat_product_count": 29,
"subcats": [
{
"cat_name": "First Subcategory",
"cat_url": "#"
},
{
"cat_name": "Second Subcategory",
"cat_url": "#"
}
]
}
You may try to implement that function to your code (I don't know JQuery so I wrote in vanilla JS);
(categoryObject) => {
if (categoryObject.subcats.length > 0) {
var result = ""
categoryObject.subcats.forEach(
(subCategoryObject) => {
var template = `<li class="subcategory">${subCategoryObject.cat_name}</li>\n`
result += template
}
return result
)
}
}
JSON
{
"cat_tr": [
{
"cat_name": "Product 1",
"cat_url": "#",
"cat_img": "img/product.png",
"cat_product_count": 29,
"cat_name_alt": [
{
"cat_name": "Product 1.1",
"cat_url": "#",
"cat_img": "img/product.png",
"cat_product_count": 1
},
{
"cat_name": "Product 1.2",
"cat_url": "#",
"cat_img": "img/product.png",
"cat_product_count": 22
}
]
},
{
"cat_name": "Product 2",
"cat_url": "#",
"cat_img": "img/product.png",
"cat_product_count": 75
},
{
"cat_name": "Product 3",
"cat_url": "#",
"cat_img": "img/product.png",
"cat_product_count": 271,
"cat_name_alt": [
{
"cat_name": "Product 3.1",
"cat_url": "#",
"cat_img": "img/product.png",
"cat_product_count": 30
},
{
"cat_name": "Product 3.2",
"cat_url": "#",
"cat_img": "img/product.png",
"cat_product_count": 40
}
]
},
{
"cat_name": "Product 4",
"cat_url": "#",
"cat_img": "img/product.png",
"cat_product_count": 71
}
]
}
JS
$(function () {
var categories = [];
$.getJSON("category.json", function (data) {
categories = data.cat_tr;
$.each(categories, function (i, f) {
var cat_index = -1;
if (typeof f.cat_name_alt !== 'undefined' && f.cat_name_alt.length > 0) {
cat_index = i;
}
var tblRow = '<li class="grid_item" data-index="' + cat_index + '">' + '' + '<div class="ic_grid">' + '<div class="cat_img">' + '<img src="' + f.cat_img + '">' + '</img>' + '</div>' + '<div class="cat_dec">' + f.cat_name + '<span>' + f.cat_product_count + '</span>' + '</div>' + '</div>' + '' + '</li>'
$(tblRow).appendTo("#cat_list")
});
});
$(document).on('click', '.grid_item', function (e) {
if ($(this).data('index') != -1) {
e.preventDefault();
$('#cat_list').html('');
var sub_categories = categories[parseInt($(this).data('index'))].cat_name_alt;
$.each(sub_categories, function (i, f) {
var cat_index = -1;
if (typeof f.cat_name_alt !== 'undefined' && f.cat_name_alt.length > 0) {
cat_index = i;
}
var tblRow = '<li class="grid_item" data-index="' + cat_index + '">' + '' + '<div class="ic_grid">' + '<div class="cat_img">' + '<img src="' + f.cat_img + '">' + '</img>' + '</div>' + '<div class="cat_dec">' + f.cat_name + '<span>' + f.cat_product_count + '</span>' + '</div>' + '</div>' + '' + '</li>'
$(tblRow).appendTo("#cat_list")
});
}
});
})
i have json like this
{
"id":"1",
"name":"Kitchen Set",
"parent_id":"0",
},
{
"id":"2",
"name":"Bedroom",
"parent_id":"0"
},
{
"id":"3",
"name":"Living Room",
"parent_id":"0"
},
{
"id":"4",
"name":"Kitchen Set",
"parent_id":"1",
"price":"1000"
},
{
"id":"5",
"name":"Meja Bar",
"parent_id":"1",
"price":"2000"
},
and i want to add price: to my javascript
here is my question i want to get the price from my json to my javascript how can i do that??
i try this but it doesnt work
load_json_data('Price');
function load_json_data(price)
{
var html_code = '';
$.getJSON('int_fur_fin.json', function(data)
}
and this is my javascript
<script>
$(document).ready(function(){
load_json_data('Interior');
function load_json_data(id, parent_id)
{
var html_code = '';
$.getJSON('int_fur_fin.json', function(data){
html_code += '<option value="">Select '+id+'</option>';
$.each(data, function(key, value){
if(id == 'Interior')
{
if(value.parent_id == '0')
{
html_code += '<option value="'+value.id+'">'+value.name+'</option>';
}
}
else
{
if(value.parent_id == parent_id)
{
html_code += '<option value="'+value.id+'">'+value.name+'</option>';
}
}
});
$('#'+id).html(html_code);
});
}
$(document).on('change', '#Interior', function(){
var Interior_id = $(this).val();
if(Interior_id != '')
{
load_json_data('Furniture', Interior_id);
}
else
{
$('#Furniture').html('<option value="">Select Furniture</option>');
}
});
});
</script>
i use this javascript code to populate my dropdown
<form>
<select name="Interior Details" id="Interior" class="form-control input-lg">
<option value="">Select Interior Details</option>
</select>
<br />
<select name="Furniture" id="Furniture" class="form-control input-lg" required >
<option value="">Select Furniture</option>
</select>
</form>
You can use array.find() method to find the matching element. Also i have modified your JSON as a array.
items.find(t=>t.parent_id ==='1');
DEMO
var items = [{
"id":"1",
"name":"Kitchen Set",
"parent_id":"0",
},
{
"id":"2",
"name":"Bedroom",
"parent_id":"0"
},
{
"id":"3",
"name":"Living Room",
"parent_id":"0"
},
{
"id":"4",
"name":"Kitchen Set",
"parent_id":"1",
"price":"1000"
},
{
"id":"5",
"name":"Meja Bar",
"parent_id":"1",
"price":"2000"
}];
var result = items.find(t=>t.parent_id ==='1');
console.log(result);
EDIT
If you want multiple elements with matching id use array.filter.
var items = [{
"id":"1",
"name":"Kitchen Set",
"parent_id":"0",
},
{
"id":"2",
"name":"Bedroom",
"parent_id":"0"
},
{
"id":"3",
"name":"Living Room",
"parent_id":"0"
},
{
"id":"4",
"name":"Kitchen Set",
"parent_id":"1",
"price":"1000"
},
{
"id":"5",
"name":"Meja Bar",
"parent_id":"1",
"price":"2000"
}];
var result = items.filter(t=>t.parent_id ==='1');
console.log(result);
Four level JSON data
{
"Asia": [
{
"continentCode": "GT113",
"regionList": [
{
"regionName": "Eastern Asia",
"regionCode": "GR128",
"Countrylist": [
{
"countryName": "China",
"countryCode": "GC302",
"subCountryList": [
{
"subCountryName": "Southern China",
"subCountryCode": "GR206"
}
]
},
{
"countryName": "Hong Kong",
"countryCode": "GC303"
}
]
},
{
"regionName": "Southern Asia",
"regionCode": "GR134",
"Countrylist": [
{
"countryName": "India",
"countryCode": "GC304"
},
{
"countryName": "Pakistan",
"countryCode": "GC309"
}
]
}
]
}
]
}
I have fetched the data upto 3 level and dispalyed upto 2 level. But cant able to fetch the 4th level data and display the 3rd and 4th level of data.
$.each(json, function (i1, object) {
alert(i1);
$.each(object, function (i2, continent) {
$.each(continent.regionList, function (i3, region) {
alert(region.regionName);
$.each(region.Countrylist, function (i4, country) {
alert(country.countryName);
if (!$("ul." + i1).is("*")) {
$("<ul />", {
"class": i1,
"html": "<li>" + region.regionName + "</li>"
}).appendTo("div").before('<b class=' + i1 + ' ><a name="' + i1 + '" >' + i1 + '</a></b>');
}else{
$("b." + i1).each(function() {
var text = this.textContent || this.innerText;
if (text === i1) {
$(this).next("ul").append("<li>" + region.regionName + "</li>");
}
});
}
/* $.each(country.subCountryList, function (i5, subCountry) {
alert(subCountry.subCountryName);
}); */
});
});
});
});
})
<div>
<ul></ul>
</div>
How to fetch the others to display as below
Asia
Eastern Asia
China -
Southern China
Hongkong
Southern Asia
Try this, using some code of #dimitar:
var json = {
"Asia": [{
"continentCode": "GT113",
"regionList": [{
"regionName": "Eastern Asia",
"regionCode": "GR128",
"Countrylist": [{
"countryName": "China",
"countryCode": "GC302",
"subCountryList": [{
"subCountryName": "Northern China",
"subCountryCode": "GR207"
}, {
"subCountryName": "Southern China",
"subCountryCode": "GR206"
}]
}, {
"countryName": "Hong Kong",
"countryCode": "GC303"
}]
}, {
"regionName": "Southern Asia",
"regionCode": "GR134",
"Countrylist": [{
"countryName": "India",
"countryCode": "GC304"
}, {
"countryName": "Pakistan",
"countryCode": "GC309"
}]
}]
}]
};
var html = '';
$.each(json, function(i1, object) {
html += '<li><b>' + i1 + '</b>';
$.each(object, function(i2, continent) {
html += '<ul>';
$.each(continent.regionList, function(i3, region) {
html += '<li><b>' + region.regionName + '</b>';
$.each(region.Countrylist, function(i4, country) {
html += '<ul><li>' + country.countryName;
if (country.subCountryList) {
html += "<ul>";
$.each(country.subCountryList, function(i5, subCountry) {
html += '<li>' + subCountry.subCountryName + '</li>';
});
html += "</ul>";
};
html += '</li></ul>';
});
html += '</li>';
});
html += '</ul>';
});
html += '</li>';
});
$('#list').html(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul id='list'></ul>
You will want to loop through all of them and print out something on each level.
Here is an example, tweak it to your liking and style it.
$.each(json, function (i1, object) {
console.log(i1);
$.each(object, function (i2, continent) {
$.each(continent.regionList, function (i3, region) {
console.log(region.regionName);
$.each(region.Countrylist, function (i4, country) {
console.log(country.countryName);
if(country.subCountryList){
$.each(country.subCountryList, function (i5, subCountry) {
console.log(subCountry.subCountryName);
});
};
});
});
});
});
Here json is your JSON you provided and we print out the list you wanted in the console.
Edited original code:
$.each(json, function (i1, object) {
$("ul").append("<li><strong>"+i1+"</li></strong>");
$.each(object, function (i2, continent) {
$.each(continent.regionList, function (i3, region) {
$("ul").append("<li><p><strong>"+region.regionName+"</li></p></strong>");
$.each(region.Countrylist, function (i4, country) {
$("ul").append("<li><p>"+country.countryName+"</li></p>");
if(country.subCountryList){
$.each(country.subCountryList, function (i5, subCountry) {
$("ul").append("<li><p>"+subCountry.subCountryName+"</li></p>");
});
};
});
});
});
});
Leave me a comment if there are still issues, I am not getting any.
Hello there I will try and keep this simple and short
I have a getJSON function that runs every 5 seconds. Now when I display the data using document.write function it dosent seem to want to update. The page is stuck in a loading loop. How can I get the data to display on my page? My JSON is fine but I will show you anyways.
<script type="text/javascript">
$.ajaxSetup ({
cache: false
});
setInterval(function(){ $.getJSON('names.json', function(data) {
for(i in data) {
document.write(data[i] + "<br/>");
}
});
},5000);
</script>
This is the JSON object
{
"one": "",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
}
Don't actually use document.write. Once the page is loaded, that will erase the page. Use (jQuery's) DOM methods to manipulate the DOM.
$.getJSON('names.json', function(data){
for(var i in data){
$('#myDiv').append(data[i]);
}
});
I would recommend you use jQuery,
I used this to create a form from my json item, I hope this helps...
function jsonFormCreator(frmJSON)
{
var createdHTML = ""; var elementType, id;
console.log(JSON.stringify(frmJSON));
for(item in frmJSON)
{
formElement = frmJSON[item]; elementType = formElement.elementType; id = formElement.id;
if(elementType == "input")
{
createdHTML += "<input id='" + id +"'";
if(formElement.type == "checkbox")
{createdHTML += " type='" + formElement.type + "' checked='" + formElement.checked + "'";}
else{createdHTML += "type='" + formElement.type + "' value='" + formElement.value + "' onclick='" + formElement.onclick + "'";}
createdHTML += "/><br>"
}
else if(elementType == "textarea")
{createdHTML += "<textarea id='" + formElement.id + "' rows='" + formElement.rows + "' cols='" + formElement.cols + "' value='" + formElement.value + "'></textarea><br>";}
else if(elementType == "select")
{
var options = formElement.values;
createdHTML += "<select id='" + formElement.id+ "'>";
for(i = 0 ; i < options.length ; i++)
{createdHTML += "<option value='" + options[i][0] + "'>" + options[i][1] + "</option>";} //Adding each option
createdHTML+= "</select><br>";
}
}
console.log("Complete");console.log(createdHTML);
document.getElementById('mainContainer').innerHTML = createdHTML;//Adding to the DOM
}
And my JSON would look like this
{
"0": {
"elementType": "input",
"id": "frm1",
"type": "text",
"value": "form Liam",
"label": "Test Text Input"
},
"itemBTN": {
"elementType": "input",
"id": "frmAlert",
"type": "button",
"onclick" : "loader(homePage);",
"value": "Home Page",
"label": ""
},
"item2": {
"elementType": "textarea",
"id": "frm2",
"rows": 5,
"cols": 30,
"value": "helddddddddlo",
"label": "Test Textarea"
},
"item3": {
"elementType": "select",
"id": "frm3",
"values": [
[
"value1",
"Pick Me"
],
[
"value2",
"UserDis2"
],
[
"value3",
"UserDis3"
],
[
"value4",
"UserDis4"
],
[
"value5",
"UserDis5"
],
[
"value6",
"UserDis6"
]
],
"label": "Test Select"
},
"item4": {
"elementType": "input",
"id": "frm4",
"label": "Checkbox",
"type": "checkbox",
"checked": true
}
}
This code adds the form in to my div tag with the id mainContainer
I know its alot of code, but i hope it helps !
You want to render dom which will contain the data, then when you get the data update the dom.
As an exceedingly simple example, on your page have a container
<div id="one"></div>
and then in your ajax success handler
$("#one").text(json.one);
This uses jquery to grab the dom element with id "one", and update its text.