Print Json data in html tabel by javascript - javascript

I have JSON data saved in this api https://api.myjson.com/bins/xeza2. I want to print the data in a table by using only JavaScript or jQuery. I have tried a few things. I have used XMLHTTP request. Json.parse() . Every method on stack.
This was the first thing I have tried
$(function () {
var people = [];
$.getJSON('https://api.myjson.com/bins/xeza2', function (data) {
$.each(data.info, function (i, f) {
var tblRow = "<tr>" + "<td>" + f.id + "</td>" +
"<td>" + f.name + "</td>" + "<td>" + f.job + "</td>" + "<td>" + f.roll + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
});
});
});

data.info is undefined hence why you weren't getting anything added to the table. You need to change it to data.ct_info.
The below code can access the JSON data in your request's response and appends it to the table. I am not sure how you want the data to look or what properties you are trying to access (hence the undefined's) that I'll leave up to you but the below should help get you started.
f.job and f.roll are non-existent properties.
$(function() {
var people = [];
$.getJSON('https://api.myjson.com/bins/xeza2', function(data) {
$.each(data.ct_info, function(i, f) {
var tblRow = "<tr>" + `<td id=${f.id}>` + "</td>" +
"<td>" + f.name + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
var users = []
//GET USER INFO
f.Qid_info.forEach((x) => {
x.user_info.forEach((y) => {
//avoid duplicates
var foundUser = users.find((user) => {
return user.id === y.id
})
if (!foundUser) {
users.push(y)
}
})
})
$.each(users, function(i, user) {
var userRow = "<tr>" + `<td id=${user.id}>` + "User's Name:" +
"</td>" +
"<td>" + user.name + "</td>" + "</tr>"
$(userRow).appendTo("#userdata tbody");
})
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='userdata'>
<tbody>
</tbody>
</table>

Related

How to delete rows other than a random row on a table(Javascript)?

I get data from the user and put it into the table by collating, I want to show a random line from the table I want to delete the other rows
function bilgi(){
var random = Math.floor(Math.random() * (allobjs.length - 1) ) + 1;
if (allobjs[random].id != 'blank'){
allobjs[random].animate({fill: 'rgb(19, 167, 236)'}, 1000);
$(function() {
$.getJSON('/static/yer.json', function(data) {
var deger = $("input[name=deger]").val()
var al = deger.split(",")
$.each(data, function(i, f) {
if(f.plaka == random){
var tblRow = "<tr>" +
"<td>" + "<img class='aaa'src='/static/bayrak.jpg' alt='' />" + "</td>" +
"<td>" + deger + "</td>" +
"<td>" + f.yerler + "</td>" +
"<td>" + f.bolge + "</td>" +
"<td>" + f.ili + "</td>" +
"<td>" + f.teskilati + "</td>" +
"<td>" + f.acm + "</td>" +
"</tr>"
$("tbody").append(tblRow);
}
});
$("tbody tr").hide()
var toplam= $("tbody tr").size()
ratgel=Math.floor(Math.random() * toplam);
$("tbody tr").eq(ratgel).show(1000)
});
});
}}
In javascript add class NOSHOW to each tr you want to hide Then using css .NOSHOW{display:none;} If you want a complete solution show your html.
something like the following might work:
At the start of your function add the following:
var tr = getElementsByTagName('tr');
for(var i = 0; i < tr.length;i++){
tr[i].className += "noshow";
}
then in you html add:
<style>
.noshow{
display:none;
}
</style>
This should work as you then append the row you want to the end of the table.
Later, when you want to display the entire table again you can use:
element.classList.remove("noshow");

How to get the value of the input fill

I want to get the value of the input fill from a function to another function but I am not sure how.
From this funtion input fill:
$("#buttonDone4").click(function () {
function productAddToTable() {
$("#table").fadeIn();
// First check if a <tbody> tag exists, add one if not
if ($("#table tbody").length == 0) {
$("#table").after("<tbody></tbody>");
}
// Append product to the table
$("#table").append(
"<tr>" +
"<td>" + document.getElementById("perimeter2").innerHTML + "</td>" +
"<td>" + "4" + "</td>" +
"<td>" + "<input type='text' name='periAns' size='10'/>" + "</td>" +
"</tr>"
);
}
productAddToTable();
$("#buttonDone4").fadeOut();
$(".p1").fadeIn();
$("#buttonCheck").fadeIn();
});
To this function:
$("#buttonCheck").click(function () {
var pa = document.getElementByName["periAns"].value;
var peri = (document.getElementById("perimeter2").innerHTML / 4);
if(peri == pa ){
console.log("yes");
}else{
console.log("no");
}
});
Put ID to the inputs and use jquery.
$("#table").append(
"<tr>" +
"<td>" + document.getElementById("perimeter2").innerHTML + "</td>" +
"<td>" + "4" + "</td>" +
"<td>" + "<input type='text' id ='periAns' size='10'/>" + "</td>" +
"</tr>"
);
}
$("#buttonCheck").click(function () {
var pa = Number($("#periAns").val()) //assuming this is an input
var peri = Number(document.getElementById("perimeter2").innerHTML)
var finPeri = peri / 4
if(finPeri == pa ){
console.log("yes");
}else{
console.log("no");
}
});

Prevent new row insert for each page refresh

I have to tables and I am appending an json file to them.
<table id="userdata" border="2">
<thead>
<th>Id</th>
<th>Title</th>
<th>TotalUnresolvedItems</th>
</thead>
<tbody></tbody>
</table>
<strong>Item2:</strong>
<table id="userdata2" border="2">
<thead>
<th>Id</th>
<th>FullName</th>
<th>TotalUnresolvedItems</th>
</thead>
<tbody></tbody>
</table>
Every time setInterval triggers it adds new rows but i would like to remove exist rows and replace it with new one.
I have tried .remove() from different places but its removing forever :(
My code looks like this.
<script type="text/javascript">
$(document).ready(function () {
refreshStatus();
setInterval(refreshStatus, 30000);
});
function refreshStatus() {
$.ajax({
type: "GET",
url: "refreshTicketStatus",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(),
dataType: "json",
success: function (data) {
repopulateTable(data);
},
error: function (errorThrown){
alert(errorThrown);
}
})
}
function repopulateTable(data) {
var parsedData = JSON.parse(data);
console.log(parsedData);
var dashboard = [];
dashboard.push(JSON.parse(data));
dashboard.forEach(function (value, index) {;
for (var key in value) {
if (value.hasOwnProperty(key)) {
if (key === 'Item1') {
value[key].forEach(function (val) {
//$('#userdata tbody').remove(9000);
var tblRow = "<tr>" + "<td>" + val.Id + "</td>" + "<td>" + val.Title + "</td>" + "<td>" + val.TotalUnresolvedItems + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
})
}
if (key === 'Item2') {
value[key].forEach(function (val) {
//$('#userdata2 tbody').remove(9000);
var tblRow = "<tr>" + "<td>" + val.Id + "</td>" + "<td>" + val.FullName + "</td>" + "<td>" + val.TotalUnresolvedItems + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata2 tbody");
})
}
}
}
});
}
</script>
I would change your repopulateDataTable function to the following. Basically I'm creating two empty variables, pass all the rows html in them and then replace all the html only once per interval.
function repopulateTable(data) {
var parsedData = JSON.parse(data);
console.log(parsedData);
var dashboard = [];
dashboard.push(JSON.parse(data));
dashboard.forEach(function (value, index) {;
var table1Rows = "";
var table2Rows = "";
for (var key in value) {
if (value.hasOwnProperty(key)) {
if (key === 'Item1') {
value[key].forEach(function (val) {
//$('#userdata tbody').remove(9000);
var tbl1Row = "<tr>" + "<td>" + val.Id + "</td>" + "<td>" + val.Title + "</td>" + "<td>" + val.TotalUnresolvedItems + "</td>" + "</tr>"
table1Rows += tbl1Row;
})
}
if (key === 'Item2') {
value[key].forEach(function (val) {
//$('#userdata2 tbody').remove(9000);
var tbl2Row = "<tr>" + "<td>" + val.Id + "</td>" + "<td>" + val.FullName + "</td>" + "<td>" + val.TotalUnresolvedItems + "</td>" + "</tr>"
table2Rows += tbl2Row;
})
}
}
}
$("#userdata tbody").html(table1Rows);
$("#userdata2 tbody").html(table2Rows);
});
}

Appending json file to html with condition

I am appending a dynamic json file to html.I would like to change the color of openticket row .td elements if value of .openticket is bigger then x number.
My code looks like:
<table id="userdata" border="2">
<thead>
<th>Department</th>
<th>OpenTickets</th>
</thead>
<tbody></tbody>
</table>
JS
function repopulateTable(data) {
var parsedData = JSON.parse(data);
console.log(parsedData);
var dashboard = [];
dashboard.push(JSON.parse(data));
dashboard.forEach(function (value, index) {;
var table1Rows = "";
for (var key in value) {
if (value.hasOwnProperty(key)) {
if (key === 'Item1') {
value[key].forEach(function (val) {
var tbl1Row = "<tr>" + "<td>" + val.Title + "</td>" + "<td>" + val.Ticketnumber + "</td>" + "</tr>"
table1Rows += tbl1Row;
})
}
}
}
$("#userdata tbody").html(table1Rows);
});
}
I have made css
.color{
color:red;
}
and tried captured the val like and add attribute:
var capture = $(val.Ticketnumber).val();
if (capture.val)>3{
$("td:second").addClass("color");
}
without success.
kindly have a look.
for (var key in value) {
if (value.hasOwnProperty(key)) {
if (key === 'Item1') {
value[key].forEach(function (val) {
var tbl1Row = "<tr " + (parseInt(val.Ticketnumber)>3?" class='color'":"") + ">" + "<td>" + val.Title + "</td>" + "<td>" + val.Ticketnumber + "</td>" + "</tr>"
table1Rows += tbl1Row;
})
}
}
}
In the above code, i have append class based on condition ("3?" color":"") + ">")

Add HTML code inside of a JS var that contains an HTML element

I need to add a list of task after to click one row in a html table I'm using knockout js. the problem is that I'm just adding de last task from my data in a row and I need to add a new TR inside my element "$taskSelected" for each task. Here is my code
self.retrieveTask = function(data, event) {
if (event.type=="click") {
var id = data.Id;
var $taskSelected = event.currentTarget.parentElement.nextElementSibling;
$.get("#Url.Action("Method", "Controller")", { id: id })
.done(function(data) {
$.each(data, function(key, value) {
var html = "<tr><td>" +
"</td>" +
"<td>" +
" <div >" +
+ value.Type +
"</div> " +
"</td>" +
"<td>" +
" <div >" +
value.Id +
"</div> " +
"</td>" +
"</tr>";
$taskSelected.innerHTML=html;
});
}).fail(function() {
alert("error");
});
};
}
the var $taskSelected contains another row "<tr> </tr>" basically Ii want to nested rows. Some advises please
Try this:
self.retrieveTask = function(data, event) {
if (event.type=="click") {
var id = data.Id;
var $taskSelected = event.currentTarget.parentElement.nextElementSibling;
$.get("#Url.Action("Method", "Controller")", { id: id })
.done(function(data) {
var html = "";
$.each(data, function(key, value) {
html += "<tr><td>" +
"</td>" +
"<td>" +
" <div >" +
+ value.Type +
"</div> " +
"</td>" +
"<td>" +
" <div >" +
value.Id +
"</div> " +
"</td>" +
"</tr>";
});
$taskSelected.innerHTML=html;
}).fail(function() {
alert("error");
});
};
}
All I did was move var html outside of your each loop. This makes sure that all your previous HTML stays inside the variable, otherwise you are overwriting html each time you run through the loop (This is why you're only outputting the last one ;) ).

Categories