I am new in html.
I am sharing my html code that get Json data from server and show in a Html-table format.
Can you change my html code such that it will have a
button between Video Link and Video Image and when I click on that button it play respective youtube video with video id of the same row.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script>
$(function() {
var people = [];
$.getJSON('https://api.myjson.com/bins/hy7g0', function(data) {
$.each(data.videoLectureListing, function(i, f) {
var tblRow = "<tr>" + "<td>" + f.Id + "</td>" +
"<td>" + f.videoName + "</td>" + "<td>" + f.date + "</td>" + "<td>" + f.time + "</td>" + "<td>" + f.video + "</td>" + "<td>" + f.image + "</td>" +
"<td>" + f.videoDuration + "</td>" + "<td>" + f.liveStatus + "</td>" + "<td>"+ "</tr>"
$(tblRow).appendTo("#userdata tbody");
});
});
});
</script>
</head>
<body>
<div class="wrapper">
<div class="profile">
<table id= "userdata" border="25">
<thead>
<th>ID</th>
<th>VIDEO NAME</th>
<th>DATE</th>
<th>TIME</th>
<th>VIDEO LINK</th>
<th>VIDEO IMAGE</th>
<th>DURACTION</th>
<th>LIVE STATUS</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</body>
</html>
i try a lot on internet but could not find anything about it please take it seriously and help me.Thank you
I had some time to kill so here's one solution for your problem:
const keys = ['Id', 'videoName', 'date', 'time', 'videoLink', 'image', 'videoDuration', 'liveStatus'];
var tableBody = document.getElementById('myTableBody');
fetch('https://api.myjson.com/bins/hy7g0').then(response => {
return response.json().then(data => {
buildTable(data.videoLectureListing);
})
});
function buildTable(fullData) {
if (fullData) {
return fullData.forEach(videoData => {
let newRow = buildRow(videoData);
tableBody.appendChild(newRow)
})
}
}
function buildRow(videoData) {
let newRow = document.createElement('tr');
keys.forEach(key => {
let domNode = undefined;
if (key === 'videoLink') {
domNode = buildAButton(videoData[key]);
} else if (key === 'image') {
domNode = buildAImage(videoData[key]);
} else {
domNode = videoData[key] ? videoData[key] : ' - ';
}
domNode = buildAColumn(domNode);
newRow.appendChild(domNode);
});
return newRow;
}
function buildAButton(videoId) {
let newButton = document.createElement('button');
newButton.innerHTML = 'Watch';
newButton.onClick = () => window.location.href = `url/path/${id}`;
return newButton;
}
function buildAColumn(object) {
let newColumn = document.createElement('td');
if (typeof object === 'string') {
newColumn.innerHTML = object;
} else {
newColumn.appendChild(object);
}
return newColumn;
}
function buildAImage(source) {
let newImage = document.createElement('img');
newImage.src = source;
return newImage;
}
Related
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>
So I have this SVG
https://github.com/Cphdat3sem2017f/StartcodeExercises/blob/master/JS/Countries_Europe.svg?short_path=6bcbfa5
I managed to hook up an eventListener and a fetch to get information on the countries when clicked on. This I have done by simply calling ex. document.getElementById("dk"). Is there a way and if so how, where i can get the id's inside the paths so I can loop through them and end up with only one call instead of one for each country?
Code:
import "bootstrap/dist/css/bootstrap.css";
const root = document.getElementById("root");
var svg = document.getElementById("svg");
const country = "https://restcountries.eu/rest/v1/alpha?codes=";
svg.addEventListener("load", function() {
var svgDoc = svg.contentDocument;
var countries = svgDoc.children;
for (let i = 0; i < countries.length; i++) {
//alert(countries[i].id);
countries[i].addEventListener("click", function(event) {
alert(countires[i]);
getCountryInfo(countries[i].id);
});
}
svgDoc.addEventListener("click", function(event) {
getCountryInfo(event.id);
});
var denmark = svgDoc.getElementById("dk");
denmark.addEventListener("click", function() {
getCountryInfo("dk");
});
var sweden = svgDoc.getElementById("se");
sweden.addEventListener("click", function() {
getCountryInfo("se");
});
var germany = svgDoc.getElementById("de");
germany.addEventListener("click", function() {
getCountryInfo("de");
});
var norway = svgDoc.getElementById("no");
norway.addEventListener("click", function() {
getCountryInfo("no");
});
var spain = svgDoc.getElementById("es");
spain.addEventListener("click", function() {
getCountryInfo("es");
});
var iceland = svgDoc.getElementById("is");
iceland.addEventListener("click", function() {
getCountryInfo("is");
});
});
function getCountryInfo(landCode) {
fetch(country + landCode)
.then(res => res.json()) //.then(res=>{ return res.json()})
.then(data => {
var table = "";
table +=
'<table border="1" style="border-spacing: 5px; table-layout: auto; width: 45%;">';
table += "<tr>";
table += "<th>Name</th>";
table += "<th>Capital</th>";
table += "<th>Also known as</th>";
table += "<th>Region</th>";
table += "<th>Population</th>";
table += "<th>Languages</th>";
table += "</tr>";
data.forEach(country => {
table += "<tr>";
table += "<td>" + country.name + "</td>";
table += "<td>" + country.capital + "</td>";
table += "<td>" + country.altSpellings + "</td>";
table += "<td>" + country.region + "</td>";
table += "<td>" + country.population + "</td>";
table += "<td>" + country.languages + "</td>";
table += "</tr>";
});
table += "</table>";
root.innerHTML = table;
});
}
As you can see we tried to get them by getting the children elements but we got stuck and couldn't seem to find answer.
Not sure what children resolves to in that context, but you can get to the paths directly via a query:
[...svgDoc.querySelectorAll('path')].forEach(path => {
path.addEventListener('click', e => {
alert(path.id);
})
})
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);
});
}
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":"") + ">")
I have an array of JavaScript JSON objects which is being parsed from a JSON formatted-string. Now what I'm doing is that I'm looping through the array and append the data to a table within the page.
jQuery Code:
$.each(objArr, function(key, value) {
var tr = $("<tr />");
$.each(value, function(k, v) {
tr.append($("<td />", {
html: v
}));
$("#dataTable").append(tr);
})
})
The code works perfectly and the table is getting populated successfully
But what I'm looking for is that, I want to add a delete button at the end of the row, by which the user will delete the row, and it also important to handle the click event in order to perform the required action
I've done this in another way, but it is not that efficient, I want to use the code above to accomplish that as it is more efficient:
for (var i = 0; i < objArr.length; i++) {
var tr = "<tr>";
var td1 = "<td>" + objArr[i]["empID"] + "</td>";
var td2 = "<td>" + objArr[i]["fname"] + "</td>";
var td3 = "<td>" + objArr[i]["lname"] + "</td>";
var td4 = "<td>" + objArr[i]["phone"] + "</td>";
var td5 = "<td>" + objArr[i]["address"] + "</td>";
var td6 = "<td >" + objArr[i]["deptID"] + "</td>";
var td7 = "<td>" + objArr[i]["email"] + "</td>";
var td8 = "<td>" + '<button id="' + objArr[i]["empID"] + '" value="' + objArr[
i]["empID"] + '" onclick="onClickDelete(' + objArr[i]["empID"] +
')">Delete</button>' + "</td></tr>";
$("#dataTable").append(tr + td1 + td2 + td3 + td4 + td5 + td6 + td7 + td8);
}
Any suggestions please?
Try something like this:
$.each(objArr, function (key, value) {
var tr = $("<tr />");
$.each(value, function (k, v) {
tr.append($("<td />", { html: v }));
tr.append("<button class='remove' />");
$("#dataTable").append(tr);
})
})
This shall append the button at the end of the tr with class remove.
Try this, I've include event handler for the each buttons inside the table.
CHANGES:
Adding Event Listener for each buttons inside the table.
Call method (function) with parameters.
Note:
I am using, fadeOut method for fading purposes only. So you can see the changes. You can change the script as your need.
EXPLAINS :
var cRow = $(this).parents('tr'); on this line we have $(this) which mean we've select the button object that you've clicked, and search the parent with tag-name tr. We need to do this because we need to take control of all data inside the tr object.
var cId = $('td:nth-child(2)', cRow).text(); has mean search second td object wich located on cRow object. And take the text from the selected td.
JQUERY REFFERENCES :
.parents()
:nth-child()
$(this) OR $(this)
$(document).ready(function() {
var jsonData = [
{id: 'A01', name: 'Fadhly'},
{id: 'A02', name: 'Permata'},
{id: 'A03', name: 'Haura'},
{id: 'A04', name: 'Aira'}
];
$.each(jsonData, function(key, val) {
var tr = '<tr>';
tr += '<td>' + (key + 1) + '</td>';
tr += '<td>' + val.id + '</td>';
tr += '<td>' + val.name + '</td>';
tr += '<td><button class="delete" data-key="'+ (key + 1) +'">Delete</button></td>';
tr += '</tr>';
$('tbody').append(tr);
});
$('button.delete').on('click', function() {
var cRow = $(this).parents('tr');
var cId = $('td:nth-child(2)', cRow).text();
var intKey = $(this).data('key');
cRow.fadeOut('slow', function() {
doDelete(cId, intKey);
});
});
function doDelete(param1, param2) {
alert('Data with\n\nID: [' + param1 + ']\nKey: [' + param2 + ']\n\nRemoved.');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" width="100%">
<thead>
<tr>
<th>#</th>
<th>Id</th>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>