I want to loop this array and show the data into a table.
var dataM = [
{
"id": "1",
"name": "My #1",
"thumbnailUrl": "image/8.gif",
"price": 20
},
{
"id": "2",
"name": "<img onerror='window.document.body.innerHTML = \"<h1>XSS</h1>\";' src=''> ",
"url": "image/10.gif",
"price": 10
}
];
Javascript function :
function loadData() {
var data = "";
for(var i = 0; i < dataM.length; i++) {
data += "<tr>";
var tempData = dataM[i];
Object.keys(tempData).forEach(function(key) {
data += "<td><code>" + tempData[key] + "</code></td>";
});
data += "</tr>";
}
var tbody = document.getElementsByTagName('tbody');
tbody[0].innerHTML = data;
}
How to show HTML element as text in webpage?
Create elements and use innerText attribute.
var dataM = [{
"id": "1",
"name": "My #1",
"thumbnailUrl": "image/8.gif",
"price": 20
},
{
"id": "2",
"name": "<img onerror='window.document.body.innerHTML = \"<h1>XSS</h1>\";' src=''> ",
"url": "image/10.gif",
"price": 10
}
];
function loadData() {
var tbody = document.getElementsByTagName('tbody')[0];
for (var i = 0; i < dataM.length; i++) {
var tr = document.createElement('tr');
var tempData = dataM[i];
Object.keys(tempData).forEach(function(key) {
var td = document.createElement('td');
var code = document.createElement('code');
code.innerText = tempData[key];
td.appendChild(code);
tr.appendChild(td);
});
tbody.appendChild(tr);
}
}
loadData();
<table>
<tbody>
</tbody>
</table>
Related
I want to display nested JSON objects.
This is what I have done so far:
orders = [
{ "custname": "Jack Smith", "mobile": "425361434", "location": "Sector 14", "slot": "12PM2PM", "value": 72.6, "items": [{ "prodcode": "PEP122", "quantity": 2 }, { "prodcode": "COK238", "quantity": 4 }] },
{ "custname": "Mary Gomes", "mobile": "723476123", "location": "Sector 22", "slot": "4PM6PM", "value": 130.60, "items": [{ "prodcode": "SUN677", "quantity": 2 }, { "prodcode": "LUX831", "quantity": 4 }, { "prodcode": "DET810", "quantity": 1 }] },
{ "custname": "Tim May", "mobile": "835099614", "location": "Pioneer Chowk", "slot": "Before 10AM", "value": 705, "items": [{ "prodcode": "GAR004", "quantity": 6 }, { "prodcode": "RB0277", "quantity": 3 }, { "prodcode": "MIR411", "quantity": 2 }] }
];
function showAllOrder() {
showtable();
}
function showtable() {
for (var i = 0; i < orders.length; i++) {
order = orders[i];
var str = "<div><div class='cell22' onclick=clicked(0)>Product</div>";
str = str + "<div class='cell22' onclick=clicked(1)>Qantity</div>";
var len = orders[i].items.length;
for (var j = 0; j < len; j++) {
for (var x = 0; x <)
//this value as simple text form above the table
var cost = ("Coustomer Name :" + order.custname);
var mob = (" Mobile :" + order.mobile);
var loc = (" Location :" + order.location);
var del = (" Delivery Slot :" + order.slot);
//this value in the form of table
var prod1 = "<div class='cell11'>" + orders[i].items[j].prodcode + "</div>";
var qty1 = "<div class='cell11'>" + orders[i].items[j].quantity + "</div>";
var row = "<div>" + cost + mob + loc + del + prod1 + qty1 + "</div>";
str = str + row;
}
}
var element = document.getElementById("mytable01");
element.innerHTML = str;
}
I'm trying to loop through some JSON data (var mydata) and mydata is an array of two elements, the second element in the array
mydata[1] is a multidimensional array, I need to display the first element i.e mydata[0] in a dt and display elements from mydata[1] in a dd within that.
I tried every option but I'm really stuck and I need any help on this. Below is my code:
var mydata = [
[{
"id": "67",
"name": "Baby & Toddler Clothing "
}, {
"id": "68",
"name": "Kids' Clothing, Shoes & Accessories"
}, {
"id": "69",
"name": "Costumes, Reenactment Theater"
}],
[
[{
"id": "572",
"name": "Baby Clothing Accessories "
}, {
"id": "573",
"name": "Baby Shoes"
}],
[{
"id": "579",
"name": "Boys Clothing [Sizes 4 & Up] "
}, {
"id": "580",
"name": "Boys Shoes"
}],
[{
"id": "588",
"name": "Costumes"
}, {
"id": "589",
"name": "Reenactment & Theater "
}]
]
]
function getCategories(id){
$.ajax({
url: '{$getcatUrl}',
type: 'POST',
data: {category_id: id},
success: function (data) {
data = jQuery.parseJSON(data);
//console.log(data); return;
if(data.length > 0){
firstdata = data[0];
secdata = data[1];
for(var i = 0; i < firstdata.length; i++) {
level_1 = firstdata[i].name;
level_1_id = firstdata[i].id;
for(var j = 0; j< secdata.length; j++){
if(secdata[i][j] !== undefined){
level_2='';
level_2 = secdata[i][j].name;
level_2_id = secdata[i][j].d;
}
console.log(level_2);
}
var dldata = $(
'<dl>'+
"<dt href='" + level_1_id + "'>" + level_1 + "</dt>"+
"<dd href='" + level_2_id + "'>" + level_2 + "</dd>"+
'</dl>'
);
}
}else{
console.log('no item for this categories');
}
},
error: function(jqXHR, errMsg) {
// handle error
console.log(errMsg);
}
});
}
The var level_1 and level_1_id works fine, but i keep getting error for variable level_2, the error says can't read property 'name' of undefined, any solution to this problem will be appreciated and am also open to new ideas about doing it better,
Essentially the problem is that you overwrite the level_1 and level_2 variables each time your for loops run. So by the time you get to the code which makes the HTML, they have been overwritten multiple times and only the last version remains, and you only print that once in any case.
This will resolve it - in this case by generating the HTML elements directly within each loop, although you could of course do it by appending to a variable and then outputting everything at the end, if that's your preference.
var data = [
[{
"id": "67",
"name": "Baby & Toddler Clothing "
}, {
"id": "68",
"name": "Kids' Clothing, Shoes & Accessories"
}, {
"id": "69",
"name": "Costumes, Reenactment Theater"
}],
[
[{
"id": "572",
"name": "Baby Clothing Accessories "
}, {
"id": "573",
"name": "Baby Shoes"
}],
[{
"id": "579",
"name": "Boys Clothing [Sizes 4 & Up] "
}, {
"id": "580",
"name": "Boys Shoes"
}],
[{
"id": "588",
"name": "Costumes"
}, {
"id": "589",
"name": "Reenactment & Theater "
}]
]
]
if (data.length > 0) {
var content = $("#content");
firstdata = data[0];
secdata = data[1];
for (var i = 0; i < firstdata.length; i++) {
var dl = $("#content").append("<dl/>");
dl.append("<dt href='" + firstdata[i].id + "'>" + firstdata[i].name + "</dd>");
for (var j = 0; j < secdata.length; j++) {
if (secdata[i][j] !== undefined) {
dl.append("<dd href='" + secdata[i][j].id + "'>" + secdata[i][j].name + "</dd>");
}
}
}
content.append(dl);
} else {
console.log('no item for this categories');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>
I am attempting to parse the values below based on a search criteria and then print the result to a table. I am able to correctly parse the desired results to console or print all the results to a table. Below is my attempt to merge both functions. I end up with a type error TypeError: obj.list[i].forEach is not a function. From searching, I believe it is because it is an object and not an array though have been unable to parse the object correctly. How can I correct the issue in order to correctly parse the object?
var obj = {
"list": [{
"name": "my Name",
"id": 12,
"type": "car owner"
},
{
"name": "my Name",
"id": 13,
"type": "car owner2"
},
{
"name": "my Name4",
"id": 14,
"type": "car owner3"
},
{
"name": "my Name4",
"id": 15,
"type": "car owner5"
}
]
};
var tableBody = "";
var columns = [];
// Create the header record.
tableBody = tableBody + "<tr>";
for (var prop in obj.list[0]) {
if (obj.list[0].hasOwnProperty(prop)) {
// Append properties such as myid, fname, lname etc.
tableBody = tableBody + ("<th>" + prop + "</th>");
// Also keep a list of columns, that can be used later to get column values from the 'data' object.
columns.push(prop);
}
}
tableBody = tableBody + "</tr>";
var results = [];
var searchField = "name";
var searchVal = "my Name";
for (var i = 0; i < obj.list.length; i++) {
// search term
if (obj.list[i][searchField] == searchVal) {
// Create the data rows.
// I get an error here:
obj.list[i].forEach(function(row) {
// Create a new row in the table for every element in the data array.
tableBody = tableBody + "<tr>";
columns.forEach(function(cell) {
// Cell is the property name of every column.
// row[cell] gives us the value of that cell.
tableBody = tableBody + "<td>" + row[cell] + "</td>";
});
tableBody = tableBody + "</tr>";
});
}
}
jQuery("#usersTable").append(tableBody);
<table border='1' id="usersTable"></table>
JSFiddle
Working version based on feedback
forEach is an iteration method for arrays, in provided code you're trying to apply this method to object, it's a wrong way. To iterate through object properties you can use for (var key in object) {"code here"}. I have corrected your code:
var obj = {
"list": [{
"name": "my Name",
"id": 12,
"type": "car owner"
},
{
"name": "my Name",
"id": 13,
"type": "car owner2"
},
{
"name": "my Name4",
"id": 14,
"type": "car owner3"
},
{
"name": "my Name4",
"id": 15,
"type": "car owner5"
}
]
};
var tableBody = "";
var columns = [];
var searchField = "name";
var searchVal = "my Name";
tableBody = tableBody + "<tr>";
for (var prop in obj.list[0]) {
if (obj.list[0].hasOwnProperty(prop)) {
tableBody = tableBody + ("<th>" + prop + "</th>");
columns.push(prop);
}
}
tableBody = tableBody + "</tr>";
for (var i = 0; i < obj.list.length; i++) {
if (obj.list[i][searchField] == searchVal) {
tableBody = tableBody + "<tr>";
for (var key in obj.list[i]) {
tableBody = tableBody + "<td>" + obj.list[i][key] + "</td>";
};
tableBody = tableBody + "</tr>";
}
}
jQuery("#usersTable").append(tableBody);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border='1' id="usersTable"></table>
Hi (sorry for my english), I have this script:
<script type="text/javascript">
$(document).ready(function() {
var idPlato = decodeURI(getUrlVars()["idPl"]);
var url = "http://localhost/plato-datos.php?idPla="+idPlato+"";
});
};
</script>
It brings me this json from my database:
[{"category":"first","name":"green","idP":"1", "count":3},
{"category":"first","name":"blue","idP":"2","count":5},
{"category":"sec","name":"peter","idP":"3", "count":3},
{"category":"sec","name":"james","idP":"4", "count":2,},
{"category":"third","name":"dog","idP":"5", "count":4}]
I need to create one radiobuton for every name and group by categores
I create a solution. Kinda ugly but it will work:
var data = [{
"category": "first",
"name": "green",
"idP": "1",
"count": 3
}, {
"category": "first",
"name": "blue",
"idP": "2",
"count": 5
}, {
"category": "sec",
"name": "peter",
"idP": "3",
"count": 3
}, {
"category": "sec",
"name": "james",
"idP": "4",
"count": 2,
}, {
"category": "third",
"name": "dog",
"idP": "5",
"count": 4
}];
var result = {};
data.map(a => {
if (result[a.category]) {
result[a.category].push(a.name);
} else {
result[a.category] = [a.name];
}
});
Object.keys(result).map(category => {
var select = document.createElement('select');
result[category].map(name => {
var option = document.createElement('option');
option.value = name;
option.text = name;
select.appendChild(option);
});
document.body.appendChild(select);
});
Im working with jquery mobile then i used autodividersSelector function for group by the category JSON object, and build a radiobuton for every name
<script type="text/javascript">
//catch the JSON from my database
$(document).ready(function() {
var idPla = decodeURI(getUrlVars()["idPl"]);
var urlAder =
"http://localhost/lista-adereso.php?idPla=" + idPla + "";
//print the radiobutons
$.getJSON(urlAder, function(resultado) {
var allfiles = '';
for (var i = 0, aderesos = null; i <
resultado.length; i++) {
aderesos = resultado[i];
allfiles +='<li><label><input type="radio" data-
status="' + aderesos.aderesoCatNom +'"
name="name" id="id" value="' +
aderesos.aderNombre +'">'+
aderesos.aderNombre + '</label></li>'; }
//Group by categories
$('#linkList')
.empty()
.append(allfiles)
.listview({
autodividers:true,
autodividersSelector: function ( li ) {
var out = li.find('input').data("status");
return out;
}
})
.listview("refresh");
});
});
</script>
how to Delete red Mark item
I add my JavaScript code
...i don't generate nested array object deleted function any one can help me
how to delete nestobj:
"value": "10"
"value": "20"
"value": "20"
<script>
$(function () {
var tr;
var obj = [{ obj1: { "name": "v1", nestobj: [{ "value": "10" }, { "value": "20" }, { "value": "20" }] } }];
obj.push({ obj1: { "name": "v2", nestobj: [{ "value": "abc" }, {"value": "xyz"}] } });
for (var i = 0; i < obj.length; i++)
{
tr = $('<tr/>');
tr.append("<td>" + obj[i].obj1.name + "</td>")
$('tbody').append(tr);
for (var j = 0; j < obj[i].obj1.nestobj.length; j++)
{
tr.append("<p>" + obj[i].obj1.nestobj[j].value + " <input type='submit' value='Delete' onclick='");'> </p>")
$('tbody').append(tr);
}
tr.append("<td>" + obj[i].obj1.nestobj.length + " <input type='submit' value='Remove All' onclick='");'> </td>")
$('tbody').append(tr);
}
});
Change your function like following:
$(function () {
var tr;
var obj = [{ obj1: { "name": "v1", nestobj: [{ "value": "10" }, { "value": "20" }, { "value": "20" }] } }];
obj.push({ obj1: { "name": "v2", nestobj: [{ "value": "abc" }, {"value": "xyz"}] } });
for (var i = 0; i < obj.length; i++)
{
tr = $('<tr/>');
tr.append("<td>" + obj[i].obj1.name + "</td>")
$('tbody').append(tr);
for (var j = 0; j < obj[i].obj1.nestobj.length; j++)
{
var $delBtn = $("<input>",{type:"submit",value:"Delete"});
var $p = $("<p>",{text:obj[i].obj1.nestobj[j].value});
$delBtn.on("click",function(){
$(this).parent().remove();
});
$p.append($delBtn);
tr.append($p);
$('tbody').append(tr);
}
var $removeAll = $("<input>",{type:"submit",value:"Remove All"});
var $col = $("<td>",{text: obj[i].obj1.nestobj.length});
$removeAll.on("click",function(){
$(this).closest("tr").find("p").remove();
});
$col.append($removeAll);
tr.append($col);
$('tbody').append(tr);
}
});
It is all about adding events to your inputs to remove the items
$(function () {
var tr;
var obj = [{ obj1: { "name": "v1", nestobj: [{ "value": "10" }, { "value": "20" }, { "value": "20" }] } }];
obj.push({ obj1: { "name": "v2", nestobj: [{ "value": "abc" }, {"value": "xyz"}] } });
for (var i = 0; i < obj.length; i++)
{
tr = $('<tr/>');
tr.append("<td>" + obj[i].obj1.name + "</td>")
$('tbody').append(tr);
for (var j = 0; j < obj[i].obj1.nestobj.length; j++)
{
var $delBtn = $("<input>",{type:"submit",value:"Delete"});
var $p = $("<p>",{text:obj[i].obj1.nestobj[j].value});
$delBtn.on("click",function(){
$(this).parent().remove();
});
$p.append($delBtn);
tr.append($p);
$('tbody').append(tr);
}
var $removeAll = $("<input>",{type:"submit",value:"Remove All"});
var $col = $("<td>",{text: obj[i].obj1.nestobj.length});
$removeAll.on("click",function(){
$(this).closest("tr").find("p").remove();
});
$col.append($removeAll);
tr.append($col);
$('tbody').append(tr);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody></tbody>
</table>