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>
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 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>
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>
Sample data:
{
"data": [
{
"name": {
"full": "JOHN",
"rank": "SENIOR"
},
"mobile": "12345"
},
{
"name": {
"full": "HENRY",
"rank": "SENIOR"
},
"mobile": "67890"
},
{
"name": {
"full": "SAM",
"rank": "JUNIOR"
},
"mobile": "54321"
}
]
}
i'm trying to get the total number of senior members from the data sample above, and i can get the data.name and data.mobile, but i can't get the 'rank' data from the parent 'name' object. can anyone please guide me to obtain the rank data. below is my javascript:
function countRank(rank) {
var i;
for (i in rank.data) {
if (rank.data[i] == "SENIOR") {
i++;
}
document.getElementById('senior').innerHTML = 'Total senior members: ' + i;
}
}
<div id="senior"></div>
Try this JSFIDDLE
function countRank(rank) {
var k=0;
for (var i=0; i< rank.data.length; i++) {
if (rank.data[i].name.rank == "SENIOR") {
k++;
}
document.getElementById('senior').innerHTML = 'Total senior members: ' + k;
}
}
countRank(rank);
You can make something like this
var rank = {
"data": [{
"name": {
"full": "JOHN",
"rank": "SENIOR"
},
"mobile": "12345"
}, {
"name": {
"full": "HENRY",
"rank": "SENIOR"
},
"mobile": "67890"
}, {
"name": {
"full": "SAM",
"rank": "JUNIOR"
},
"mobile": "54321"
}]
};
function countRank(rank) {
var i = 0,
arr = rank.data;
for (var j = 0; j < arr.length; j++) {
for (var prop in arr[j]) {
if (arr[j][prop].rank == "SENIOR") {
i++;
}
document.getElementById('senior').innerHTML = 'Total senior members: ' + i;
}
}
}
countRank(rank);
myObject.data[0].name.rank
>>> "SENIOR"
Assuming that whole object is called obj:
var i=0;
for (i=0; i < obj.data.length; i++) {
console.log(obj.data[i].name.rank);
}
function countRank(rank) {
var count = 0;
var arr = rank.data;
for (var i=0; i<arr.length; i++) {
var name = arr[i].name;
if (name.rank == "SENIOR") {
count++;
}
}
alert(count);
}
I checked it and it worked well.
Using jQuery you can find rank from above data easily.
checkout sample on jsFiddle
http://jsfiddle.net/uBnfu/
$.each(jsonData.data, function (index, value) {
alert(value.name['rank']);
});
I have some JSON data (simple array of objects) .
var input= [
{
"cat": "some",
"id": "0"
},
{
"cat": "some",
"id": "1"
},
{
"cat": "some/category",
"id": "2"
},
{
"cat": "some/category/sub",
"id": "3"
},
{
"cat": "some/other",
"id": "4"
},
{
"cat": "some/thing/different",
"id": "5"
},
{
"cat": "some/thing/different",
"id": "6"
},
{
"cat": "yet/another",
"id": "7"
}
]
I wanted to generate nested html list out of it based on categories:
some
0
1
category
2
sub
3
other
4
thing
different
5
6
yet
another
7
My first step was to create empty nested object using the function:
createNestedObject = function(base, names) {
var = 0;
var results = [];
while (i < names.length) {
base = base[names[i]] = base[names[i]] || {};
results.push(i++);
}
return results;
}
Next i populated it with data using by spliting "cat" strings and pushing "ids" in loop (ex. some.category.sub.ids.push(7))
The final result was:
var output =
{
"some": {
"ids": [
"0",
"1"
],
"category": {
"ids": [
"2"
],
"sub": {
"ids": [
"3"
]
}
},
"other": {
"ids": [
"4"
]
},
"thing": {
"different": {
"ids": [
"5",
"6"
]
}
},
"yet": {
"another": {
"ids": [
"7"
]
}
}
}
}
However, the structure somewhat problematic because i don't know the key names and the nesting depth in advance.
How to generate nested html list out of "output" or "input" data presented here?
How about this?
Example
JS
function ToHTML(input){
var html = '<ul>';
for(var key in input){
if(input[key] instanceof Array){
for(var i = 0; i < input[key].length; i++){
html += '<li>' + input[key][i] + '</li>';
}
}else{
html += '<li>' + key + ToHTML(input[key]) + '</li>';
}
}
html += '</ul>';
return html;
}
function ToNestedObject(input){
var i, y, len = input.length, parts, partsLen, obj = {}, prev;
for(i = 0; i < len; i++){
parts = input[i].cat.split('/');
partsLen = parts.length;
prev = obj;
for(y = 0; y < partsLen; y++){
prev[parts[y]] = prev[parts[y]] || {};
prev = prev[parts[y]];
}
if(!prev.ids){
prev.ids = [];
}
prev.ids.push(input[i].id);
}
return obj;
}
var input= [
{
"cat": "some",
"id": "0"
},
{
"cat": "some",
"id": "1"
},
{
"cat": "some/category",
"id": "2"
},
{
"cat": "some/category/sub",
"id": "3"
},
{
"cat": "some/other",
"id": "4"
},
{
"cat": "some/thing/different",
"id": "5"
},
{
"cat": "some/thing/different",
"id": "6"
},
{
"cat": "yet/another",
"id": "7"
}
];
document.getElementById('test').innerHTML = ToHTML(ToNestedObject(input));
HTML
<div id='test'></div>
The array is converted into object tree
function buildTreeObject ( input ) {
var obj = {}, n ;
input.forEach( function( v ){
var keys = v.cat.split('/'),
n = obj ;
keys.forEach( function( k ){
if ( !n[k]) {
n[k] = {};
}
n = n[k];
});
n[ v.id ] = v.id ;
});
return obj;
}
and we need a function to build html
function buildHtml( obj , ul ) {
for (i in obj) {
var li = document.createElement('li');
li.innerHTML = i;
ul.appendChild( li );
if ( typeof(obj[i])== "object" ) {
childUl = document.createElement('ul');
li.appendChild( childUl );
buildHtml(obj[i], childUl );
}
}
}
and make html use of input ( ie ur array )
var ul = document.createElement('ul'),
tree = buildTreeObject( input ) ;
buildHtml( tree ,ul );
var div = document.createElement('div');
div.appendChild( ul );
console.log( div.innerHTML );
Which prints desired ul li list
You can see result in http://jsfiddle.net/r3RWL/
Since you added jquery under tags, I have written solution to your problem in jQuery. Here is the code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<div id="someDiv">
</div>
<script>
function prepareNestedStructure(input) {
var output = {},
catLevels,
currentCat;
$.each(input, function(index, catObject) {
catLevels = catObject.cat.split('/');
currentCat = output;
$.each(catLevels, function(index, name) {
if(!currentCat[name])
currentCat[name] = {};
currentCat = currentCat[name];
});
currentCat[catObject.id] = catObject.id;
});
return output;
}
function fillList(parentListEl, node) {
$.each(node, function(key, value) {
parentListEl.append('<li>' + key + '</li>');
if(jQuery.type(value) === 'object') {
var childEl = $('<ul></ul>');
parentListEl.append(childEl);
fillList(childEl, value);
}
});
}
var input= [
{
"cat": "some",
"id": "0"
},
{
"cat": "some",
"id": "1"
},
{
"cat": "some/category",
"id": "2"
},
{
"cat": "some/category/sub",
"id": "3"
},
{
"cat": "some/other",
"id": "4"
},
{
"cat": "some/thing/different",
"id": "5"
},
{
"cat": "some/thing/different",
"id": "6"
},
{
"cat": "yet/another",
"id": "7"
}
];
var output = prepareNestedStructure(input);
var ulDomElement = $('<ul></ul>');
fillList(ulDomElement, output);
$('#someDiv').append(ulDomElement);
</script>
</body>
</html>
what about this?
transform_deeply_nested_object = (dno) ->
result = ""
for key, value of dno
if value instanceof Array
result += "<ul>"
for elem in value
result += "<li>" + elem + "</li>\n"
result += "</ul>"
else
result += "<ul><li>" + key + "</li>"
result += transform_deeply_nested_object value
result += "</ul>"
Attention: Not tested!
Attention: This requires all leafs to be elements of an array always.