i would like to display only details of Linda using JSON. However, I am clueless on how to do it. Need some advice, thanks!
The output should show the updated table with only "Linda" instead of my current output.
Actual question:
Using JSON, modify the mobile of Linda to 88885555, and display only the details of Linda.
My employees object is supposed to be from .json file but i couldnt find the format to insert into this post. Hence, i combined it into my .js file.
var employees = [
{
"Name": "Tony",
"Mobile": 99221111,
"Email": "tony#json.com"
},
{
"Name": "Linda",
"Mobile": 98981111,
"Email": "linda#json.com"
},
{
"Name": "Patrick",
"Email": "patrick#json.com"
},
{
"Name": "Isabella",
"Mobile": 99552222
}
];
employees[1].Mobile = 88885555;
function buildHtmlTable() {
var columns = addAllColumnHeaders(employees);
for (var i = 0; i < employees.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = employees[i][columns[colIndex]];
if (cellValue == null) {
cellValue = "";
}
row$.append($('<td/>').html(cellValue));
}
$("#employeeTable").append(row$);
}
}
// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(employees) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < employees.length; i++) {
var rowHash = employees[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1) {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$("#employeeTable").append(headerTr$);
return columnSet;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body onLoad="buildHtmlTable()">
<table id="employeeTable" border="1"></table>
</body>
You can create a function that accepts an "employee name", .not() and .is() to match any <td> elements within the <tr> where .textContent is equal to the argument passed to the function, chain .hide() to set the display of the matched elements to "none".
To display all <tr> elements you can use $("#employeeTable tr").show().
Substituted using jQuery(function(){}) for onload attribute event handler at <body> element.
var employees = [{
"Name": "Tony",
"Mobile": 99221111,
"Email": "tony#json.com"
},
{
"Name": "Linda",
"Mobile": 98981111,
"Email": "linda#json.com"
},
{
"Name": "Patrick",
"Email": "patrick#json.com"
},
{
"Name": "Isabella",
"Mobile": 99552222
}
];
employees[1].Mobile = 88885555;
function buildHtmlTable() {
var columns = addAllColumnHeaders(employees);
for (var i = 0; i < employees.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = employees[i][columns[colIndex]];
if (cellValue == null) {
cellValue = "";
}
row$.append($('<td/>').html(cellValue));
}
$("#employeeTable").append(row$);
}
}
// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(employees) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < employees.length; i++) {
var rowHash = employees[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1) {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$("#employeeTable").append(headerTr$);
return columnSet;
}
<!DOCTYPE html>
<html>
<head>
<title>Task 1</title>
<!-- using of jquery, calling external js file -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<table id="employeeTable" border="1">
</table>
<script>
$(function() {
buildHtmlTable();
function hideRow(employeeName) {
return $("#employeeTable tr").not(function(index, element) {
return $(element.cells).is(function(i, el) {
return el.textContent === employeeName
});
}).hide();
}
hideRow("Linda");
});
</script>
</body>
</html>
If I understood your question correctly you could do something like I did below. I used setTimeout so you can see the transition from your original output to the updated output:
function buildTable(arr) {
let html = "<table border='1' style='width: 100%'>";
for (let i = 0; i < arr.length; i++) {
html += `<tr>
<td>${arr[i].Name || ''}</td>
<td>${arr[i].Mobile || ''}</td>
<td>${arr[i].Email || ''}</td>
</tr>`;
}
html += "</table>";
return html;
}
function init() {
const LINDA_IDX = 1;
container.innerHTML = buildTable(employees);
setTimeout(function() { //
//Update Linda's phone number
employees[LINDA_IDX].Mobile = 88885555;
//Show just Linda in the table
container.innerHTML = buildTable([employees[LINDA_IDX]])
}, 2000);
}
var employees = [{
"Name": "Tony",
"Mobile": 99221111,
"Email": "tony#json.com"
}, {
"Name": "Linda",
"Mobile": 98981111,
"Email": "linda#json.com"
}, {
"Name": "Patrick",
"Email": "patrick#json.com"
}, {
"Name": "Isabella",
"Mobile": 99552222
}];
var container = document.querySelector('#container');
init();
After 2 seconds setTimeout will execute showing Linda's updated info:<br />
<div id="container"></div>
Related
I'm getting some json data from the services and bind those values in the table format in the child window. Click on link in the child window, should close child window and redirect the url in parent current window.
<html>
<head>
<title>sample</title>
<script type="text/javascript">
var childWindow;
function GenerateStudentsTable() {
var jsondata = {
"school": {
"students": [{
"studentId": "Test1",
"Name": "Message01"
},
{
"studentId": "Test2",
"Name": "Message2"
}, {
"studentId": "Test3",
"Name": "Message3"
}
],
"redirectURL" : "https://www.google.com/search"
}
}
var query = "students";
var table = document.createElement("TABLE");
table.border = "1";
var headerLabels = ["Id", "Name"]
var headerLabelsCount = headerLabels.length;
var row = table.insertRow(-1);
for (var i = 0; i < headerLabelsCount; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = headerLabels[i];
row.appendChild(headerCell);
}
var jsonLength = Object.keys(jsondata.school.students).length;
for (var i = 0; i < jsonLength; i++) {
row = table.insertRow(-1);
for (var j = 0; j < headerLabelsCount; j++) {
var cell = row.insertCell(-1);
if (j == 0) {
cell.innerHTML = '' + jsondata.school.students[i].studentId + '';
} else {
cell.innerHTML = '' + jsondata.school.students[i].Name + '';
}
}
}
childWindow = window.open("", "Title", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top=" + (screen.height - 400) + ",left=" + (screen.width - 840));
childWindow.document.body.innerHTML = table.outerHTML;
}
function redirectToParentWindow()
{
childWindow.close();
window.location.href =jsondata.school.redirectURL;
}
</script>
</head>
<body>
<input type="button" value="Generate Table" onclick="GenerateStudentsTable()" />
<hr />
<div id="dvTable">
</div>
</body>
</html>
I have no issues in the binding data in the child window but i'm not sure how to close the child window and redirect to link in parent window. Thanks in advance
Below code changes are working as expected.
<html>
<head>
<title>sample</title>
<script type="text/javascript">
var childWindow, redirectUrl;
function GenerateStudentsTable() {
var jsondata = {
"school": {
"students": [{
"studentId": "Test1",
"Name": "Message01"
},
{
"studentId": "Test2",
"Name": "Message2"
}, {
"studentId": "Test3",
"Name": "Message3"
}
],
"redirectURL": "https://www.google.com/search"
}
}
var query = "students";
var table = document.createElement("TABLE");
table.border = "1";
var headerLabels = ["Id", "Name"]
var headerLabelsCount = headerLabels.length;
var row = table.insertRow(-1);
for (var i = 0; i < headerLabelsCount; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = headerLabels[i];
row.appendChild(headerCell);
}
var jsonLength = Object.keys(jsondata.school.students).length;
for (var i = 0; i < jsonLength; i++) {
row = table.insertRow(-1);
for (var j = 0; j < headerLabelsCount; j++) {
var cell = row.insertCell(-1);
if (j == 0) {
cell.innerHTML = '' + jsondata.school.students[i].studentId + '';
} else {
cell.innerHTML = '' + jsondata.school.students[i].Name + '';
}
}
}
redirectUrl = jsondata.school.redirectURL.concat("?q=query");
childWindow = window.open("", "Title", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top=" + (screen.height - 400) + ",left=" + (screen.width - 840));
childWindow.document.body.innerHTML = table.outerHTML;
}
function redirectToParentWindow() {
childWindow.close();
window.location.href = redirectUrl;
}
</script>
</head>
<body>
<input type="button" value="Generate Table" onclick="GenerateStudentsTable()" />
<hr />
<div id="dvTable">
</div>
</body>
</html>
I want to dynamically add checkboxes to multiple rows in an html table, without having to add input type ="checkbox" for each . Is this possible?
The code snippet for making the table and a function 'check()' to add check boxes is given below...but it does not work. please help.
// Builds the HTML Table out of myList json data.
function buildHtmlTable(myList) {
var columns = addAllColumnHeaders(myList);
for (var i = 0; i < myList.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) {
cellValue = "";
}
row$.append($('<td/>').html(cellValue));
}
$("#excelDataTable").append(row$);
}
}
// Adds a header row to the table and returns the set of columns.
function addAllColumnHeaders(myList) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < myList.length; i++) {
var rowHash = myList[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1) {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
//check();
}
// check();
}
//check();
}
$("#excelDataTable").append(headerTr$);
return columnSet;
check();
}
function check() {
for (var i = 0; i < myList.length; i++) {
$('<input />', {
type: 'checkbox',
id: 'id' + i,
})
.appendTo("#excelDataTable");
}
}
You can add the checkboxes after the table is created.
Below, you can see the updated code. Your table creation works perfect. But you were trying to append the checkboxes to the table itself, not td elements.
In $(document).ready function below, you can see that I create the table first and after that call check() function. It basicly creates a new checkbox for each row, wraps it in a td and put that into the row.
I also added a change event method for the first checkbox to control all the others.
// Builds the HTML Table out of myList json data.
function buildHtmlTable(myList) {
var columns = addAllColumnHeaders(myList);
for (var i = 0; i < myList.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) {
cellValue = "";
}
row$.append($('<td/>').html(cellValue));
}
$("#excelDataTable").append(row$);
}
}
// Adds a header row to the table and returns the set of columns.
function addAllColumnHeaders(myList) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < myList.length; i++) {
var rowHash = myList[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1) {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
//check();
}
// check();
}
//check();
}
$("#excelDataTable").append(headerTr$);
return columnSet;
//check();
}
function check() {
// foreach row in the table
// we create a new checkbox
// and wrap it with a td element
// then put that td at the beginning of the row
var $rows = $('#excelDataTable tr');
for (var i = 0; i < $rows.length; i++) {
var $checkbox = $('<input />', {
type: 'checkbox',
id: 'id' + i,
});
$checkbox.wrap('<td></td>').parent().prependTo($rows[i]);
}
// First checkbox changes all the others
$('#id0').change(function(){
var isChecked = $(this).is(':checked');
$('#excelDataTable input[type=checkbox]').prop('checked', isChecked);
})
}
$(document).ready(function() {
var myList = [{
"ASN": "AS9498 BHARTI Airtel Ltd.",
"COUNTRY": "IN",
"IP": "182.72.211.158\n"
}, {
"ASN": "AS9874 StarHub Broadband",
"COUNTRY": "SG",
"IP": "183.90.37.224"
}, {
"ASN": "AS45143 SINGTEL MOBILE INTERNET SERVICE PROVIDER Singapore",
"COUNTRY": "SG",
"IP": "14.100.132.200"
}, {
"ASN": "AS45143 SINGTEL MOBILE INTERNET SERVICE PROVIDER Singapore",
"COUNTRY": "SG",
"IP": "14.100.134.235"
}]
buildHtmlTable(myList);
check();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="excelDataTable"></table>
I have a json file in my website project, like this:
[
{
"id": "1",
"name": "ramesh",
"phone": "12345",
"salary": "50000"
},
{
"id": "2",
"name": "suresh",
"phone": "123456",
"salary": "60000"
}
]
Here it is the sample data, It has 4 columns but i don't know that my json data which i will get, will have how many number of columns. I am trying to create a dynamic html table from this json data. This is the code i have write now:
<script>
$(document).ready(function () {
var jsonitems = [];
$.getJSON("json.json", function (data) {
var totalColumns = Object.keys(data[0]).length;
var columnNames = [];
columnNames = Object.keys(data[0]);
//Create a HTML Table element.
var table = document.createElement("TABLE");
table.border = "1";
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < totalColumns; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = columnNames[i];
row.appendChild(headerCell);
}
above code is working, I am facing problem when i try to insert data rows, below is the code for that which is not working:
//Add the data rows.
//for (var i = 1; i < data.length; i++) {
// row = table.insertRow(-1);
// for (var j = 0; j < totalColumns; j++) {
// var cell = row.insertCell(-1);
// cell.innerHTML = customers[i][j];
// }
//}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
});
});
</script>
Please help me with that.
Thanks
The way you are accessing the cell data is wrong. For example, to access id of first object, you've to do data[0]["id"], instead your code tries to do data[0][0]. Working example of your code:
var data = [{
"id": "1",
"name": "ramesh",
"phone": "12345",
"salary": "50000"
},
{
"id": "2",
"name": "suresh",
"phone": "123456",
"salary": "60000"
}
];
var totalColumns = Object.keys(data[0]).length;
var columnNames = [];
columnNames = Object.keys(data[0]);
//Create a HTML Table element.
var table = document.createElement("TABLE");
table.border = "1";
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < totalColumns; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = columnNames[i];
row.appendChild(headerCell);
}
// Add the data rows.
for (var i = 0; i < data.length; i++) {
row = table.insertRow(-1);
columnNames.forEach(function(columnName) {
var cell = row.insertCell(-1);
cell.innerHTML = data[i][columnName];
});
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
<div id="dvTable"></div>
Based on what I can interpret, you can just do this. Access each object inside the array, then use the keys to map your values.
But what you've written as your example code and your provided data seems different.
let data = [
{
"id": "1",
"name": "ramesh",
"phone": "12345",
"salary": "50000"
},
{
"id": "2",
"name": "suresh",
"phone": "123456",
"salary": "60000"
}
];
var table = document.getElementById("table");
for (let item of data) {
row = table.insertRow(-1);
for (let key in item) {
var cell = row.insertCell(-1);
cell.innerHTML = item[key];
}
}
<table id="table">
</table>
Define empty table in HTML file, and append thead and tbody in js file, fill the td content in js file according to data read from JSON file.
Question: How to fix the 1st and 2nd column of this dynamic table?
It is just an example. You can try this.
var myList = [
{ "name": "abc", "age": 50 },
{ "age": "25", "hobby": "swimming" },
{ "name": "xyz", "hobby": "programming" }
];
function buildHtmlTable(selector) {
var columns = addAllColumnHeaders(myList, selector);
for (var i = 0; i < myList.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) cellValue = "";
row$.append($('<td/>').html(cellValue));
}
$(selector).append(row$);
}
}
function addAllColumnHeaders(myList, selector) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < myList.length; i++) {
var rowHash = myList[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1) {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$(selector).append(headerTr$);
return columnSet;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onLoad="buildHtmlTable('#excelDataTable')">
<table id="excelDataTable" border="1">
</table>
</body>
I've got a small problem in my javascript which i am stuck on for a while now.
What i did is :
Create an empty table.
Generate the tr/td tags and values inside the table(from JSON-object).
for (var i = 0 ; i < myList.length ; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0 ; colIndex < columns.length ; colIndex++) {
var cellValue = myList[i][columns[colIndex]];
if(colIndex == columns.indexOf("type"))
{
var box$ = $('<td/>');
if(cellValue == "Organisation")
box$.addClass( "uk-badge uk-badge-danger" );
else
box$.addClass( "uk-badge uk-badge-primary" );
box$.html(cellValue);
row$.append(box$);
}
else
{
var box$ = $('<td/>');
box$.html(cellValue);
box$.attr('contenteditable','true');
box$.attr('onkeyup','updateJSON('+colIndex+','+i+')');
row$.append(box$);
}
}
$(selector).append(row$);
}
table looks fine:
td contenteditable="true" onkeyup="updateJSON(3,0)">Timmy/td>
The problem occurs when the table is generated and i edit a field. the 'onkeyup' does not 'fire' while it should. Replacing the 'onkeyup' with an 'onclick' works just fine. I have no clue why this does not work, can anybody help?
var myList = [
{
"id": 1,
"name": "arnold"
},
{
"id": 2,
"name": "hans"
},
{
"id": 3,
"name": "jack"
},
{
"id": 4,
"name": "Peter"
}];
function loadDoc3() {
$("#RelationDataTable tr").remove();
buildHtmlTable('#RelationDataTable');
}
// Builds the HTML Table out of myList.
function buildHtmlTable(selector) {
var columns = addAllColumnHeaders(myList, selector);
for (var i = 0 ; i < myList.length ; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0 ; colIndex < columns.length ; colIndex++) {
var cellValue = myList[i][columns[colIndex]];
if(colIndex == columns.indexOf("type"))
{
var box$ = $('<td/>');
if(cellValue == "Organisation")
box$.addClass( "uk-badge uk-badge-danger" );
else
box$.addClass( "uk-badge uk-badge-primary" );
box$.html(cellValue);
row$.append(box$);
}
else
{
var box$ = $('<td/>');
box$.html(cellValue);
box$.attr('contenteditable','true');
box$.attr('onkeyup','updateJSON('+colIndex+','+i+')');
//box$.click(function() {
// alert( "Handler for .keyup() called." );
//});
row$.append(box$);
}
}
$(selector).append(row$);
}
}
var currentcolumns = [];
// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(myList) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0 ; i < myList.length ; i++) {
var rowHash = myList[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1 && key != "id") {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$("#RelationDataTable").append(headerTr$);
currentcolumns = columnSet;
return columnSet;
}
function updateJSON(xx,y)
{
var cellValue = myList[y][currentcolumns[xx]];
alert(document.getElementById("RelationDataTable").rows[y+1].cells[xx].firstChild.nodeValue);
myList[y][currentcolumns[xx]] = document.getElementById("RelationDataTable").rows[y+1].cells[xx].firstChild.nodeValue;
x = 2;
}
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<input id="searchname" type="text" name="InsertSearchname" onkeyup="loadDoc3()"><h2>Search Contact</h2>
<table id="RelationDataTable">
<thead>
</thead>
<tbody>
</tbody>
</table>
</body>
contenteditable="true" should be set for your <td> elements, not on the <table>.
Otherwise the td will not trigger an event.
So add box$.attr('contenteditable','true'); in your loop.