Need to parse a Json object and append it to a table - javascript

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function myFunction() {
var abc, obj, i, j;
abc = {
"cars": [
'{"model":"Sentra", "doors":4, "lol":["hi","hello","hahahaha"]}',
'{"model":"Maxima", "doors":4,"lol":["hi","hello","hahahaha"]}',
'{"model":"Skyline", "doors":2,"lol":["hi","hello","hahahaha"]}'
]
}
var obj = JSON.parse(abc);
var theader = "<tr><th>Title</th><th>Author</th><th>year</th></tr>";
document.getElementById("dtable").appendChild(theader);
var x;
for (i = 0; i < abc.cars.length; i++) {
x += "<tr><td>" + obj.cars[i].model + "</td><td>" + obj.cars[i].doors + "</td><td>" + obj.cars[i].lol[0] + "</td></tr>";
document.getElementById("dtable").appendChild(x);
}
};
</script>
</head>
<body>
<div class="container" ,id="dsjson">
<button type="button" onclick="myFunction()">display json</button>
<br><br>
<table id="dtable"></table>
</div>
</body>
</html>
The nested json data needs to be displayed in the HTML table. On clicking the button the table displaying the json must appear. We can use JavaScript or JQuery For that one. In my example, I am using JavaScript. I don't know where it's going wrong.

you dont need to parse abc since it is already an object, but you need to parse each car object
<html>
<head>
<script type="text/javascript">
function myFunction(){
var abc,obj,i,j;
abc =
{"cars": [
' {"model":"Sentra", "doors":4, "lol":["hi","hello","hahahaha"]}',
'{"model":"Maxima", "doors":4,"lol":["hi","hello","hahahaha"]}',
'{"model":"Skyline", "doors":2,"lol":["hi","hello","hahahaha"]}'
]}
var obj = abc;
var theader = "<tr><th>Title</th><th>Author</th><th>year</th></tr>";
document.getElementById("dtable").appendChild(theader);
var x;
for (i=0; i < abc.cars.length; i++) {
abc.cars[i]=JSON.parse(abc.cars[i]);
x += "<tr><td>" + obj.cars[i].model + "</td><td>" + obj.cars[i].doors+ "</td><td>" + obj.cars[i].lol[0]+ "</td></tr>" ;
document.getElementById("dtable").appendChild(x);
}
};
</script>
</head>
<body>
<div class ="container" ,id = "dsjson">
<button type="button" onclick="myFunction()">display json</button>
<br><br>
<table id="dtable"></table>
</div>
</body>
</html>```

Your data is already an object. No need to parse it. The javascript interpreter has already parsed it for you.
If you want to add content using html strings, you can use insertAdjacentHTML in Vanilla.js
const dtable = document.getElementById("dtable");
const obj = {
"cars": [{
"model": "Sentra",
"doors": 4,
"lol": [
"hi",
"hello",
"hahahaha"
]
},
{
"model": "Maxima",
"doors": 4,
"lol": [
"hi",
"hello",
"hahahaha"
]
},
{
"model": "Skyline",
"doors": 2,
"lol": [
"hi",
"hello",
"hahahaha"
]
}
]
};
const cars = obj.cars;
const theader = "<tr><th>Title</th><th>Author</th><th>year</th></tr>";
function myFunction() {
for (let i = 0; i < cars.length; i++) {
if (i == 0) {
dtable.insertAdjacentHTML('beforeend', theader);
}
let row = `<tr>
<td>${cars[i].model}</td>
<td>${cars[i].doors}</td>
<td>${cars[i].lol[0]}</td>
</tr>`;
dtable.insertAdjacentHTML('beforeend', row);
}
};
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="container" ,id="dsjson">
<button type="button" onclick="myFunction()">display json</button>
<br><br>
<table id="dtable"></table>
</div>
</body>
</html>

You have few issues in your code.
First of all appendChild() accepts a dom node as the parameter but you are providing htmlString, try insertAdjacentHTML() OR innerHTML instead.
Then you are modifying the DOM inside the loop with the previous value, this will duplicate the result.
You can try the following way:
function myFunction(){
var abc,i,j;
var abc = {
"cars": [
{"model":"Sentra", "doors":4, "lol":["hi","hello","hahahaha"]},
{"model":"Maxima", "doors":4,"lol":["hi","hello","hahahaha"]},
{"model":"Skyline", "doors":2,"lol":["hi","hello","hahahaha"]}
]
};
var theader = "<tr><th>Title</th><th>Author</th><th>year</th></tr>";
document.getElementById("dtable").innerHTML = theader;
var x ='';
for (i=0; i < abc.cars.length; i++) {
x += "<tr><td>" + abc.cars[i].model + "</td><td>" + abc.cars[i].doors+ "</td><td>" + abc.cars[i].lol[0]+ "</td></tr>";
}
document.getElementById("dtable").innerHTML += x;
};
<div class ="container" id = "dsjson">
<button type="button" onclick="myFunction()">display json</button>
<br><br>
<table id="dtable"></table>
</div>

Use some JSON validator tools like https://jsonlint.com/ or similar.
Now no need for abc var.
var obj = {
cars: [
{
model: "Sentra",
doors: 4,
lol: ["hi", "hello", "hahahaha"]
},
{
model: "Maxima",
doors: 4,
lol: ["hi", "hello", "hahahaha"]
},
{
model: "Skyline",
doors: 2,
lol: ["hi", "hello", "hahahaha"]
}
]
};

I think you are a bit confused with appendChild and innerHTML.
If you want to use appendChild you will need to provide an HTML element, however, if you just want to add HTML text, use innerHTML.
abc is already a JSON object, so you don't need to parse it again, however, you will want to parse the lol prop inside.
Here are those changes and some small improvements, using object destructuring to clean some things up a little.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function myFunction() {
var abc, obj, i, j;
abc = {
"cars": [
'{"model":"Sentra", "doors":4, "lol":["hi","hello","hahahaha"]}',
'{"model":"Maxima", "doors":4,"lol":["hi","hello","hahahaha"]}',
'{"model":"Skyline", "doors":2,"lol":["hi","hello","hahahaha"]}'
]
}
var theader = "<tr><th>Title</th><th>Author</th><th>year</th></tr>";
document.getElementById("dtable").innerHTML = (theader);
var x = "";
for (i = 0; i < abc.cars.length; i++) {
const car = JSON.parse(abc.cars[i])
const { model, doors, lol } = car
x += "<tr><td>" + model + "</td><td>" + doors + "</td><td>" + lol[0] + "</td></tr>";
}
document.getElementById("dtable").innerHTML += x;
};
</script>
</head>
<body>
<div class="container" ,id="dsjson">
<button type="button" onclick="myFunction()">display json</button>
<br><br>
<table id="dtable"></table>
</div>
</body>
</html>

Related

Why is my script getting stuck before it reaches the loop?

<div id="content-1"></div>
<div id="content-2"></div>
<div id="content-3"></div>
<script type="text/javascript">
// Write HTML with JS
document.getElementById("content-1").innerHTML = '<h1>Title</h1>...and more';
document.getElementById("content-2").innerHTML = 'hello';
let value = '';
for(let i = 0; i < aR.length; i++){
value += aR[i]['name'] + ": " + aR[i]['price'] + "<br/>";
}
document.getElementById("content-3").innerHTML = 'hi!';
</script>
For some reason my code seems to never reach the third document.getElementById statement. The value for that third statement is supposed to be value not the string hi; I thought the initial problem was with value so I set content-3 as the string "hi" but now I've realized that my script doesn't even run till that point.
Does anyone know what is going on and how to fix it?
as Muhammad Asif said, its aR declare?
for example just add these and will work
var aR = {
0: { name: "XX", price: "55" },
1: { name: "YY", price: "55" }
};
all the code for example
<div id="content-1"></div>
<div id="content-2"></div>
<div id="content-3"></div>
<script type="text/javascript">
var aR = {
0: { name: "XX", price: "55" },
1: { name: "YY", price: "55" }
};
// Write HTML with JS
document.getElementById("content-1").innerHTML = '<h1>Title</h1>...and more';
document.getElementById("content-2").innerHTML = 'hello';
let value = '';
for (let i = 0; i < aR.length; i++) {
value += aR[i]['name'] + ":" + aR[i]['price'] + "<br/>";
}
document.getElementById("content-3").innerHTML = 'hi!';
</script>
by declaring the aR object will run all the code
first of all, only run this line and check whether your script is running or not.
document.getElementById("content-1").innerHTML = '<h1>Title</h1>...and more';
check, is this line is displayed?
second, What is this aR? Did you declare it before?
aR.length;

How to sort by alphabetically (ascending and descending) in JavaScript

HTML:
<section class="cd-gallery">
<ul id="courses">
</ul>
<div class="cd-fail-message">No results found</div>
</section>
<ul>
<li><input id="buttonaz" type="button" value="Course name(a-z)"/></li>
<li><input id="buttonza" type="button" value="Course name(z-a)"/></li>
<li><input id="buttonlu" type="button" value="Last updated"></li>
<ul>
JavaScript:
var public_spreadsheet_url = 'https://docs.google.com/spreadsheets/..."
function init() {
Tabletop.init( { key: public_spreadsheet_url,
callback: showInfo,
simpleSheet: true } );
}
window.addEventListener('DOMContentLoaded', init);
function sortAZ(a, b) {
var x = a.Course.toLowerCase();
var y = b.Course.toLowerCase();
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortZA(a, b) {
var x = a.Course.toLowerCase();
var y = b.Course.toLowerCase();
return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}
function showInfo(data) {
var bodyContent = '';
var sheetUrlRoot = 'https://docs.google.com/spreadsheets/d/';
var buttonaz = document.getElementById("buttonaz");
var buttonza = document.getElementById("buttonza");
console.log(data)
for (var i = 0; i < data.length; i++) {
var sheetUrl = sheetUrlRoot + data[i].ActionId;
var c = data[i].Course;
var courseName = '<div class=\"courseName\">' + c + '</div>';
var designer = data[i]['Designer'].toLowerCase();
var numHolds = data[i]['On Hold']
if (numHolds > 0) {
bodyContent += '<li class="color-2 course mix ' + designer + ' "style="background-color: #E89696";>' + courseName + statusList+ sheetLink+ '</li>';
} else if (numHolds <= 0){
bodyContent += '<li class="color-1 course mix ' + designer + ' "style="background-color: #C2D5BE";>' + courseName + statusList+ sheetLink+'</li>';
}
}
document.getElementById('courses').innerHTML = bodyContent;
document.getElementById('buttonaz').onclick = data.sort(sortAZ);
document.getElementById('buttonaz').onclick = data.sort(sortZA);
}
Hi Stack Overflow users,
I have imported data using tabletop.js to display a set of courses that my university has in hand. However, I cannot have it to display the courses sorting alphabetically from a-z, as well as from z-a when the buttons "Course name (a-z)" and "Course name (z-a)" are clicked. The data are displayed when the page is first loaded, but will not do anything when I click the sorting buttons.
Please help and any input will be appreciated!
P.S. I'm also filtering the courses by the name of designer using mixitup jQuery plugin.
Refer the code which have two button , one is for sort aZ and one is for sort Za . Click on Expand snippet , you will see two button , click on them and enjoy sorting
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array Sort</h2>
<p>Click the buttons to sort the array alphabetically or numerically.</p>
<button onclick="myFunction1()">Sort Az</button>
<button onclick="myFunction2()">Sort zA</button>
<p id="demo"></p>
<script>
var points = ["z", "b", "d", "a"];
var data1=Array.prototype.slice.call(points);
console.log('Za Sort ',data1.sort().reverse());
document.getElementById("demo").innerHTML = points;
function myFunction1() {
points.sort();
document.getElementById("demo").innerHTML = points;
}
function myFunction2() {
document.getElementById("demo").innerHTML = data1.sort().reverse();
}
</script>
</body>
</html>
If incoming data is array use javascript built in sort() function to sort data
var data = ["z", "b", "d", "a"];
data.sort();
console.log('Ascending order aZ ',data)
data.reverse();
console.log('Descending order zA',data);
output
Ascending order ["a", "b", "d", "z"]
Descending order["z", "d", "b", "a"]
If you want to use library https://underscorejs.org/#
var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.sortBy(stooges, 'name');

The loop is supposed to create 10 paragraphs and insert text, but the text only appears in one

In firebug console 10 paragraphs is displayed in the source code of the page, but only the first one contains text.
It looks like the loop inserted the text each time into the same paragraph, overwriting it's value. How to insert the text into each paragraph?
(function(){
var names = ["Yaakov", "John", "Jen", "Jason", "Paul",
"Frank", "Larry", "Paula", "Laura", "Jim"];
for (var name in names) {
var new_par = document.createElement("p");
new_par.id = "new_par";
var greeter = document.getElementById("greeter");
greeter.appendChild(new_par);
var firstChar = names[name].charAt(0).toLowerCase();
if (firstChar === 'j') {
//byeSpeaker.speak(names[name]);
document.getElementById("new_par").innerHTML = "Goodbye" + " " + names[name];
} else {
//helloSpeaker.speak(names[name]);
document.getElementById("new_par").innerHTML = "Hello" + " " + names[name];
}
}
})();
Here's the HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Module 4 Solution Starter</title>
</head>
<body>
<h1>Module 4 Solution Starter</h1>
<div id="greeter"></div>
<script src="SpeakHello.js"></script>
<script src="SpeakGoodBye.js"></script>
<script src="script.js"></script>
</body>
</html>
The problem is that you are creating ten nodes with the same id, new_par, so you are always getting a reference to the first #new_par when you do
document.getElementById("new_par").innerHTML
The simplest solution will be to use the reference you already have, no need to call getElementById.
new_par.innerHTML = ...
The problem is that each paragraph has the same id. I added a counter variable, to add at the end of id...
(function(){
var counter = 0;
var names = ["Yaakov", "John", "Jen", "Jason", "Paul",
"Frank", "Larry", "Paula", "Laura", "Jim"];
for (var name in names) {
var new_par = document.createElement("p");
var par_id = "new_par" + counter;
new_par.id = par_id;
var greeter = document.getElementById("greeter");
greeter.appendChild(new_par);
var firstChar = names[name].charAt(0).toLowerCase();
if (firstChar === 'j') {
//byeSpeaker.speak(names[name]);
document.getElementById(par_id).innerHTML = "Goodbye" + " " + names[name];
} else {
//helloSpeaker.speak(names[name]);
document.getElementById(par_id).innerHTML = "Hello" + " " + names[name];
}
counter++;
}
})();

live search with jquery and json

I want to make a live search and then select those suggestions for further implementation!But it doesn't put values in the select field.In other words,option tag is not working!!!
here is the code!!!
//index.php
<html lang="en"><head>
<meta charset="utf-8">
<title>Live Search</title>
</head>
<body>
<div id="searcharea">
<label for="search">live search</label>
<p>Enter the name</p>
<input type="search" name="search" id="search" placeholder="name or info">
</div>
<div>
<div id="top"></div>
<div id="center"></div>
<div id="bottom"></div>
</div>
<script src="jquery-1.12.2.min.js"></script>
<script src="basic.js"></script>
</body>
</html>
//location.json
[
{
"name":"Barot Bellingham",
},
{
"name":"Jonathan G. Ferrar II",
},
{
"name":"Hillary Hewitt Goldwynn-Post",
},
{
"name":"Hassum Harrod",
},
{
"name":"Jennifer Jerome",
},
{
"name":"LaVonne L. LaRue",
},
{
"name":"Constance Olivia Smith",
},
{
"name":"Riley Rudolph Rewington",
},
{
"name":"Xhou Ta",
}
]
//basic.js
$('#search').keyup(function()
{
var searchField=$('#search').val();
var myExp=new RegExp(searchField,"i");
var slct_start='<select>';
$('#top').html(slct_start);
$.getJSON('location.json',function(data)
{
var output='<ul class="searchresults">';
$.each(data,function(key,val){
if(val.name.search(myExp)!=-1)
{
output='<option '+'value='+val.name+'>'+val.name+'</option>';
}
});
$('#center').html(output);
});//get json
var slct_end='</select>';
$('#bottom').html(slct_end);
});
Instead of this KeyUp function,
You can use the Jquery AutoComplete functionality for easy search.
Try that one.
Refer this AutoComplete search in Jquery
I found that your location.json's data is not standard, it should like this:
[
{
"name":"Barot Bellingham"
},
{
"name":"Jonathan G. Ferrar II"
},
{
"name":"Hillary Hewitt Goldwynn-Post"
},
{
"name":"Hassum Harrod"
},
{
"name":"Jennifer Jerome"
},
{
"name":"LaVonne L. LaRue"
},
{
"name":"Constance Olivia Smith"
},
{
"name":"Riley Rudolph Rewington"
},
{
"name":"Xhou Ta"
}
]
first we put a html file as index.html
<div class="container">
<h4 class="publish-work" >PUBLISHED WORKS AVAILABLE</h4>
<br>
<input type="search" class="search" name="search" >
<br>
<br>
<table id="datalist" class="table table-bordered" style="height: 400px; overflow-y: auto;">
<thead>
<th>S.no</th>
<th>Name</th>
<th>Price</th>
</thead>
<tbody>
</tbody>
</table>
then add a script.js file
$(document).ready(function()
{
var table_object = [];
for(var i=0; i<1500; i++)
{
var object1 = [''];
object1[0] = randomString() ;
object1[1] = i+1;
object1[2] = i*10/2;
table_object.push( object1 );
}
console.log( table_object );
function render ( arraylist ) {
var html = '';
for(var i=0;i<arraylist.length;i++)
{
//var html = '';
html += '<tr>';
html += '<td>'+arraylist[i][0]+'</td>';
html += '<td>'+arraylist[i][1]+'</td>';
html += '<td>'+arraylist[i][2]+'</td>';
html += '</tr>';
//html1 += html;
//console.log(html);
}
console.log(html);
$("#datalist tbody").html(html);
}
render( table_object );
$(".search").on("keyup", function() {
var value = $(this).val();
var anotherval = [''];
var dummyarray = [];
for ( i=0; i<table_object.length; i++ )
{
if ( table_object[i]["name"].indexOf(value) != -1 )
{
dummyarray.push(table_object[i]);
}
}
render(dummyarray);
});
function randomString ()
{
var randomStringArray = [];
var stringSet = "abcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < 100; i++) {
var maxLength = Math.floor(Math.random() * (10 - 5 + 1)) + 5;
var String = "";
for (var j = 0; j < maxLength; j++) {
String += stringSet[Math.floor(Math.random() * stringSet.length)];
}
randomStringArray.push(String);
}
return String;
}
});
thats it..

JavaScript function to generate dropdowns / remove dropdown menus

I am trying to add and remove dropdown <select>s to a form on a button click. This is the code I have currently. I could have sworn I had this working last night, but when I went to work some more on my project this morning, the dropdowns wouldn't add / remove correctly.
function DropDowns(){
this.counter = 0;
this.addDropdown = function (divname) {
var newDiv = document.createElement('div');
var html = '<select name="cookie' + this.counter + '">', i;
for (i = 0; i < cookies_drop.length; i++) {
html += "<option value='" + cookies_drop[i] + "'>" + cookies_drop[i] + "</option>"
}
html += '</select>';
newDiv.innerHTML = html;
document.getElementById(divname).appendChild(newDiv);
this.counter++;
}
this.remDropdown = function() {
$('#dropdowns-container').find('div:last').remove();
this.counter--;
}
}
var dropsTest = new DropDowns();
HTML:
<form action='' method=post id="dropdowns-container">
<button id="add_cookie" type="button" onclick="dropsTest.addDropdown('dropdowns-container');">add cookie</button>
<button id="rem_cookie" type="button" onclick="dropsTest.remDropdown();">remove cookie</button>
<input name="cookies" type=submit value="submit">
</form>
I can only figure out the main problem may be on the server side when you create the cookies_drop variable using json_encode.
Other problems may reside in:
A test on the parameter of addDropdown function is suggested to check if it's valid
In the function remDropdown the decrement of the counter variable must be done only if the element is actually removed
You mixed jQuery and javaScript
Instead of using directly the createElement, making the code more simple and readable, you used the innerHTML property.
So, my snippet is:
// I assume you used something like:
// var cookies_drop = JSON.parse( '<?php echo json_encode($data) ?>' );
var cookies_drop = [{text: "Text1", val: "Value1"},
{text: "Text2", val: "Value2"},
{text: "Text3", val: "Value3"}];
function DropDowns() {
this.counter = 0;
this.addDropdown = function (divname) {
var divEle = document.querySelectorAll('form[id=' + divname + ']');
if (divEle.length != 1) {
return; // error
}
var newDiv = document.createElement('div');
var newSelect = document.createElement('select');
newSelect.name = 'cookie' + this.counter;
newDiv.appendChild(newSelect);
for (var i = 0; i < cookies_drop.length; i++) {
var newOption = document.createElement('option');
newOption.value = cookies_drop[i].val;
newOption.text = cookies_drop[i].text;
newSelect.appendChild(newOption);
}
divEle[0].appendChild(newDiv);
this.counter++;
}
this.remDropdown = function () {
var lastDiv = document.querySelectorAll('#dropdowns-container div:last-child');
if (lastDiv.length == 1) {
lastDiv[0].parentNode.removeChild(lastDiv[0]);
this.counter--;
}
}
}
var dropsTest = new DropDowns();
<form action="" method="post" id="dropdowns-container">
<button id="add_cookie" type="button" onclick="dropsTest.addDropdown('dropdowns-container');">add cookie</button>
<button id="rem_cookie" type="button" onclick="dropsTest.remDropdown();">remove cookie</button>
<input name="cookies" type=submit value="submit">
</form>

Categories