How to display json data in html table using jQuery ? and How can i remove case sensitive while searching the result?
expected output
How can i display the result in my table? How can i achieve this?
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}
];
/* Get Result */
function getResult() {
/* Read value from input fields */
var skills = $("#skills").val() || '',
email = $("#email").val() || '',
username = $("#username").val() || '';
var result = [],
i;
for (i = 0; i < data.length; i++) {
if ((skills !== '' && data[i]["skills"].indexOf(skills) !== -1) || (data[i]["email"] === email) || (
data[i]["username"] === username)) {
result.push(data[i]);
}
}
return result;
};
$('#submit').click(function onClick() {
var output = getResult();
console.log(output);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="skills" type="text" placeholder="skills">
<input id="email" type="email" placeholder="mail id">
<input id="username" type="text" placeholder="username">
<input id="submit" type="submit" value="submit">
You need to create a table and need to append coming data to this table using below code:-
$('#submit').click(function onClick() {
var output = getResult();
var html = '';
$.each(output,function(key,value){
html +='<tr>';
html +='<td>'+ value.username + '</td>';
html +='<td>'+ value.email + '</td>';
html +='<td>'+ value.skills + '</td>';
html +='</tr>';
});
$('table tbody').html(html);
});
To do case-insensitive comparison use .toUpperCase()
Working snippet:-
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}
];
/* Get Result */
function getResult() {
/* Read value from input fields */
var skills = $("#skills").val() || '',
email = $("#email").val() || '',
username = $("#username").val() || '';
var result = [],
i;
for (i = 0; i < data.length; i++) {
if ((skills !== '' && data[i]["skills"].toUpperCase().indexOf(skills.toUpperCase()) !== -1) || (data[i]["email"].toUpperCase() === email.toUpperCase()) || (
data[i]["username"].toUpperCase() === username.toUpperCase())) {
result.push(data[i]);
}
}
return result;
};
$('#submit').click(function onClick() {
var output = getResult();
var html = '';
$.each(output,function(key,value){
html +='<tr>';
html +='<td>'+ value.username + '</td>';
html +='<td>'+ value.email + '</td>';
html +='<td>'+ value.skills + '</td>';
html +='</tr>';
});
$('table tbody').html(html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="skills" type="text" placeholder="skills">
<input id="email" type="email" placeholder="mail id">
<input id="username" type="text" placeholder="username">
<input id="submit" type="submit" value="submit">
<br>
<table>
<thead>
<tr>
<th>Username</th>
<th>Email ID</th>
<th>Core Skills</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
You can use Data-table jQuery plugin to generate table from jsondirectly like
$('#tableId').DataTable({
data: jsonData,
columns: [
{ data: 'username',title:'Username'},
{ data: 'emailId',title:'EmailId'},
{ data: 'skils',title:'Core Skills'}
],
"search": {
"caseInsensitive": false
}
});
For More detail follow Data-table jQuery Plugin.
Here is the code
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}
];
function BindDataToTable(d,obj){
var keys=Object.keys(d[0]);
var table=document.createElement("table");
var trHead=document.createElement("tr");
jQuery(keys).each((index,item)=>{
var th=document.createElement("th");
th.innerHTML=item;
trHead.appendChild(th)
})
table.appendChild(trHead)
for(var i=0;i<d.length;i++){
var tr=document.createElement("tr");
jQuery(keys).each((index,item)=>{
var td=document.createElement("td");
td.innerHTML=d[i][item];
tr.appendChild(td)
})
table.appendChild(tr)
}
jQuery(obj).append(table);
}
BindDataToTable(data,"#tableElement")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="skills" type="text" placeholder="skills">
<input id="email" type="email" placeholder="mail id">
<input id="username" type="text" placeholder="username">
<input id="submit" type="submit" value="submit">
<div id="tableElement">
</div>
Related
I want to create a table build from two different JSON files. One of them shows me the names, work position, and age. The other shows me emails, name and also their work occupation. However, they have different names for the same values and are in different order. I used mustache.js to render the data, but I noticed the files have different order, so the names did not match the emails, as I build my table from fetching the two different files.
var text = '[
{
"occupation": "SV",
"name": "Mark",
"age":21
},
{
"occupation": "PE",
"name": "Jeff",
"age":24
},
{
"occupation": "MH",
"name": "Steven",
"age":20
},
{
"occupation": "GP",
"name": "Briana",
"age":22
}
]'
var text2 = '[
{
"position": "PE",
"id": "Jeff",
"Email":"jeff#gmail.com"
},
{
"position": "SV",
"id": "Mark",
"Email":"mark#gmail.com"
},
{
"position": "GP",
"id": "Briana",
"Email":"briana#gmail.com"
},
{
"position": "MH",
"id": "Steven",
"Email":"steven#gmail.com"
}
]'
var obj = JSON.parse(text);
$(document).ready(function() {
var template = $('#user-template').html();
for(var i in obj)
{
var info = Mustache.render(template, obj[i]);
$('#ModuleUserTable').html(info);
}
});
var obj2 = JSON.parse(text2);
$(document).ready(function() {
var template2 = $('#user-template2').html();
for(var i in obj2)
{
var info = Mustache.render(template2, obj2[i]);
$('#ModuleUserTable2').html(info);
}
});
<table border="1" id = "ModuleUserTable">
<tr>
<th>FullName</th>
<th>Work</th>
<th>Age</th>
</tr>
</table>
<script id="user-template" type="text/template">
<tr>
<td>{{name}}</td>
<td>{{occupation}}</td>
<td>{{age}}</td>
</tr>
</script>
<table border="1" id = "ModuleUserTable2">
<tr>
<th>FullName</th>
<th>Work</th>
<th>Email</th>
</tr>
</table>
<script id="user-template2" type="text/template">
<tr>
<td>{{id}}</td>
<td>{{position}}</td>
<td>{{Email}}</td>
</tr>
</script>
I want to combine the data, so I can have all values in one table. So I have name, age, work, and email in one. I also have a 3rd Json from witch I can get their names only, but in the file the name of it is also different and it is only the value that is the same so it looks like "user135":"Jeff". I was thinking of doing something like this, but I do not know how to do it right:
function(nameuser)
for (var name) {
if(name."user135 == "Jeff"){
jQuery( Mustache.render($('#ModuleUserTable').html(), name)).appendTo("#ModuleUserTable2");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
This code will complete the first list items from second list via matching id and name properties. You can explore the result situation of list1 inside of the table;
var list1 = [
{
"occupation": "SV",
"name": "Mark",
"age":21
},
{
"occupation": "PE",
"name": "Jeff",
"age":24
},
{
"occupation": "MH",
"name": "Steven",
"age":20
},
{
"occupation": "GP",
"name": "Briana",
"age":22
}
];
var list2 = [
{
"position": "PE",
"id": "Jeff",
"Email":"jeff#gmail.com"
},
{
"position": "SV",
"id": "Mark",
"Email":"mark#gmail.com"
},
{
"position": "GP",
"id": "Briana",
"Email":"briana#gmail.com"
},
{
"position": "MH",
"id": "Steven",
"Email":"steven#gmail.com"
}
];
function findSource(name){
let temp = null;
$(list2).each((index,object)=>(temp==null && object.id == name) ? temp=object : 0);
return temp;
}
function complete(object){
let source = findSource(object.name);
if(source!=null&&source!=undefined){
object.position = source.position;
object.Email = source.Email;
}
}
function addToTable(object){
let tr= $("<tr>");
$(tr).append("<td>" + object.occupation + "</td>");
$(tr).append("<td>" + object.name + "</td>");
$(tr).append("<td>" + object.age + "</td>");
$(tr).append("<td>" + object.position + "</td>");
$(tr).append("<td>" + object.Email + "</td>");
$("#ModuleUserTable2").append(tr);
}
$(list1).each((index,item)=>{
complete(item);
addToTable(item);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" id = "ModuleUserTable2">
</table>
I'm trying to display the data in the table depending on search. How can I achieve this?
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}
]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="skills">
<input type="email" placeholder="mail id">
<input type="text" placeholder="username">
<input type="submit" value="submit">
Expected o/p:
search any field ex:
input: java,
output :john and jane profiles
input:sql
output: only jane profile //he is the person who has sql skill
if nothing matches show 0 results
User can search using any one field, if any one item matches that profile should be displayed in my table. How can I do this? Can anyone please help me sort it out?
/* Dataset*/
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}];
/* Get Result */
function getResult() {
/* Read value from input fields */
var skills = $("#skills").val() || '',
email = $("#email").val() || '',
username = $("#username").val() || '';
var result = [],
i;
for(i = 0; i < data.length; i++) {
if ((skills !== '' && data[i]["skills"].indexOf(skills) !== -1) || (data[i]["email"] === email) || (data[i]["username"] === username)) {
result.push(data[i]);
}
}
return result;
};
$('#submit').click(function onClick() {
console.log(getResult()); // print expected data
});
<script
src=
"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input id="skills" type="text" placeholder="skills">
<input id="email" type="email" placeholder="mail id">
<input id="username" type="text" placeholder="username">
<input id="submit" type="submit" value="submit">
in ES6 you can do it :
results = array.filter (x=>x.username.search(search_txt));
let my_list = [{"username":"John Doe","email":"jn#gmail.com","skills":"java,c,html,css"},{"username":"Jane Smith","email":"js#gmail.com","skills":"java,sql"},{"username":"Chuck Berry","email":"cb#gmail.com","skills":"vuejs"}];
results = my_list.filter (x => x.skills.search('java')!=-1);
console.log(results);
//result is : [{"username":"John Doe","email":"jn#gmail.com","skills":"java,c,html,css"},{"username":"Jane Smith","email":"js#gmail.com","skills":"java,sql"}]
<!DOCTYPE html>
<html>
<head>
<title>SEARCH</title>
</head>
<body>
<input type="text" placeholder="skills" id="skills">
<input type="email" placeholder="mail id" id="email">
<input type="text" placeholder="username" id="username">
<input type="submit" value="submit" id="submit">
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Skills</th>
</tr>
<tr id="search">
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}];
$('#submit').click(function(){
var skills = $('#skills').val();
var email = $('#email').val();
var username = $('#username').val();
if(username){
search(username);
}
});
function search(username){
var name = username;
var html ;
data.forEach(function(currentValue, index, array){
if(currentValue.username == name){
html = "<td>"+currentValue.username+"</td>"+
"<td>"+currentValue.email+"</td"+
"<td>"+currentValue.skills+"</td>"
;
}else{
html = "Result Not Found";
}
});
return $('#search').html(html);
}
</script>
</body>
</html>
You can make a search function for skills like this:
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}];
var skills = "java,c";
function search(){
result = [];
var setSkills = skills.split(","); console.log(setSkills);
data.map((current,index)=>{
let currentSkills = current.skills.split(","); //console.log(currentSkills);
// currentSkills = ["java", "c", "html", "css"]
// setSkills = ["java", "c"] ;
// length of set currentSkills == length of set (currentSkills + setSkill) --> mean setSkills is subset of currentSkills
let bool = Array.from(new Set(currentSkills) ).length == Array.from(new Set(currentSkills.concat(setSkills)) ).length;
if(bool)
console.log(data[index]);
});
}
<input type="text" placeholder="skills">
<input type="email" placeholder="mail id">
<input type="text" placeholder="username">
<input type="submit" onclick="search();" value="submit">
When i tried to click the edit radio button the details will be displayed in the concerned boxes but the existing details in the table is deleted. Here my requirement is to use single array/scope variable for edit, display and delete. But no use for loop while edit/delete. Here i done the changes but no proper way of work. my html index.html as follows
<div ng-controller="employeeController">
<header><h1>Employee Details</h1></header>
<form name="myForm" novalidate>
<table id="myTable" cellspacing="0" cellpadding="4">
<tr>
<td><label> Employee Id </Label></td>
<td><input type="text" name="eid" data-ng-model="employees.EmployeeId" data-ng-required="true" ng-disabled="newEmployees"/></td>
</tr>
<tr>
<td><label> FirstName </Label></td>
<td><input type="text" name="fname" data-ng-model="employees.FirstName" data-ng-required="true"/></td>
</tr>
<tr>
<td><label> LastName </Label></td>
<td><input type="text" name="lname" data-ng-model="employees.LastName" data-ng-required="true"/></td>
</tr>
<tr>
<td><label> Gender </Label></td>
<td>
<input type="radio" name="gender" data-ng-change="employees.Gender" value ="Male" data-ng-model="employees.Gender"/> Male
<input type="radio" name="gender" data-ng-change="employees.Gender" value ="Female" data-ng-model="employees.Gender"/>Female
</td>
</tr>
<tr>
<td><label> Email </Label></td>
<td><input type="text" name="email" data-ng-model="employees.Email" data-ng-required="true"/></td>
</tr>
<tr>
<td><label> Account </Label></td>
<td><input type="text" name="account" data-ng-model="employees.Account" data-ng-required="true"/></td>
</tr>
<tr>
<td><input type="hidden" data-ng-model="employees.EmployeeId"></td>
</tr>
</table>
<button name="btnSave" data-ng-click="saveEmployeeRecord(employees)" class="userbutton">Save</button>
<button name="btnReset" data-ng-click="resetEmployeeRecord()" class="userbutton">Reset</button>
</form>
<table border="2" cellspacing="0" cellpadding="4">
<tr style="color: blue">
<th style="width:100px">Employee Id</th>
<th style="width:150px">FirstName</th>
<th style="width:150px">LastName</th>
<th style="width:90px">Gender</th>
<th style="width:150px">Email</th>
<th style="width:60px">Account</th>
<th>Action</th>
</tr>
<tr style="color:green" data-ng-repeat="emp in employees">
<td>{{emp.EmployeeId}}</td>
<td>{{emp.FirstName}}</td>
<td>{{emp.LastName}}</td>
<td>{{emp.Gender}}</td>
<td>{{emp.Email}}</td>
<td>{{emp.Account}}</td>
<td>
<input type="radio" name="process" data-ng-click="editEmployee(emp, employees.indexOf(emp))"> Edit
<input type="radio" name="process" data-ng-click="DeleteEmployee(employees.indexOf(emp))"> Delete
</td>
</tr>
</table>
</div>
javascript app.js
var employeeApp = angular.module("myApp",[]);
employeeApp.controller("employeeController", function($rootScope, $scope, $http) {
$http.get('data/employees.json').success(function(data) {
$rootScope.employees = data;
});
var empId = 12342;
$rootScope.saveEmployeeRecord = function(emp) {
if($rootScope.employees.EmployeeId == null) {
$rootScope.employees.EmployeeId = empId++;
$rootScope.employees.push(emp);
}
else {
for(i in $rootScope.employees) {
if($rootScope.employees[i].EmployeeId == emp.EmployeeId) {
$rootScope.employees[i]= emp;
}
}
}
//$rootScope.employees = {};
}
$rootScope.resetEmployeeRecord = function() {
angular.copy({}, $rootScope.employees);
}
$rootScope.editEmployee = function(emp, indx) {
//$rootScope.emp = $rootScope.employees;
if($rootScope.employees[indx].EmployeeId == emp.EmployeeId) {
$rootScope.employees = angular.copy($rootScope.employees[indx]);
}
}
$rootScope.DeleteEmployee = function(idx) {
var result = confirm("Are you sure want to delete?");
if (result) {
$rootScope.employees.splice(idx,1);
return true;
}
else {
return false;
}
//for(i in $rootScope.employees) {
//if($rootScope.employees[i].EmployeeId == idx) {
//$rootScope.employees = {};
//}
//}
}
});
employees.json file:
[
{
"EmployeeId": "61234",
"LastName": "Anderson",
"FirstName": "James",
"Gender": "Male",
"Email": "james_anderson#infosys.com",
"Account": "Boeing"
},
{
"EmployeeId": "512458",
"LastName": "Cambell",
"FirstName": "Mike",
"Gender": "Male",
"Email": "mike.cambell#infosys.com",
"Account": "Boeing"
},
{
"EmployeeId": "712785",
"LastName": "Swachengar",
"FirstName": "Andrew",
"Gender": "Male",
"Email": "andrew.swachengar#infosys.com",
"Account": "Cisco"
},
{
"EmployeeId": "712734",
"LastName": "Anderson",
"FirstName": "James",
"Gender": "Male",
"Email": "james.anderson#infosys.com",
"Account": "Apple"
},
{
"EmployeeId": "61245",
"LastName": "Green",
"FirstName": "Rachael",
"Gender": "Female",
"Email": "rachael_green#infosys.com",
"Account": "Boeing"
},
{
"EmployeeId": "61347",
"LastName": "Brown",
"FirstName": "Jackualine",
"Gender": "Female",
"Email": "jackualine_brown#infosys.com",
"Account": "Boeing"
}
]
You need to assign the selected item to a model which you have to associate in your edit/save form. And then when "save" is clicked, you need to update the original data with the updated data. Here's an example of how that would work:
$rootScope.saveEmployeeRecord = function() {
for(k in $scope.selectedEmployee){
$scope.selectedEmployee[k] = $scope.selectedEmployeeCopy[k];
}
}
$rootScope.resetEmployeeRecord = function() {
$rootScope.selectedEmployeeCopy = null;
}
$rootScope.editEmployee = function(emp) {
$rootScope.selectedEmployee = emp;
$rootScope.selectedEmployeeCopy = angular.copy($rootScope.selectedEmployee);
}
Here, I am making a copy of your original employee, and updating the copy. When saved, the copy will replace the original employee. When cancelled, it will be simply ignored. Here's a working fiddle based on your code.
Edit: based on feedback, updated the save and delete method which were not working as expected. Also updated the jsFiddle.
Edit2: Removed for loops and relpaced with passing array index
$rootScope.saveEmployeeRecord = function() {
$rootScope.employees.splice($rootScope.selectedIndex, 1,$rootScope.selectedEmployeeCopy);
}
$rootScope.resetEmployeeRecord = function() {
$rootScope.selectedEmployeeCopy = null;
$rootScope.selectedIndex = null;
}
$rootScope.editEmployee = function(emp, ind) {
$rootScope.selectedIndex = ind;
$rootScope.selectedEmployee = emp;
$rootScope.selectedEmployeeCopy = angular.copy($rootScope.selectedEmployee);
}
$rootScope.DeleteEmployee = function(emp, ind) {
var result = confirm("Are you sure want to delete?");
if (result) {
$rootScope.employees.splice(ind, 1);
$rootScope.selectedEmployeeCopy = null;
$rootScope.selectedIndex = null;
return true;
}
else {
return false;
}
}
You can Pass id as like this with your index in your radio button.
<button class="btn btn-default" ng-click="editBook(add.id, $index);" type="submit">Edit</button>
See my controller:
$scope.editBook = function(id,index) {
$scope.show1=false;
$scope.show=true;
$http.get(appurl + 'user/adds/' + id + '.json')
.success(function(data, status, headers, config) {
$scope.user= data;
angular.copy($scope.user, $scope.copy);
});
};
I followed a video tutorial but I failed to output the result regardless many hours works. The output I expect is when user type some name to search for a company for example, companies' name will be show as a suggestion list. After select a certain company, more details of the company will be shown such as location, opening hours. I attach my HTML, JavaSCript and example JSON file here.
<body>
<div id="searcharea">
<label for="search">Ajax search</label>
<p> enter the name </p>
<input type="search" name="search" id="search" placeholder="company
name" />
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script src="script.js"></script>
</body>
</html>
$(#search).keyup(function() {
var searchFiled = $('#search').val();
var myExp = new RegExp(searchField, "i");
$.getJSON('mylist.json', function(data) {
var output = '<ul class="searchresults">';
$.each(data, function(key, val) {
if (val.user.search(myExp) != -1) {
output += '<li>';
output += '<h2>' + val.company + '</h2>';
output += '</li>';
}
});
output += '</ul>';
$('$update').html(output);
});
});
{
"data": [{
"user_id": "1",
"name": "Lala",
"address": "somewhere on the world",
"company": "big company",
}, {
"user_id": "2",
"name": "Tom",
"address": "USA",
"company": "CocaCola",
}]
"reminds": 0,
"message": "this is a message",
"myID": 0
}
I am developing a web application and I use jQuery 1.5 and JavaScript for the main functionality of the app. I connect from my app to a RESTful interface where I GET information for a person.
I use this function to retrieve the information from the json page:
var jqxhr = $.getJSON("example.json", function() { // store the data in a table }
My data in json format are like but I will get as a result more than one persons having the format of:
[{"person":{"time":"2010-02-18T17:59:44","id":1,"name": "John","age":60, "updated_at":"010-02-18T17:59:44"}}]
How can I store only the id, the name and the age of the person in a JavaScript table (to be more precise an array) and ignore the rest of the information?
Here is the specific JavaScript / jQuery you need, based on the MAP function.
var originalData = [
{ "person": { "time": "2010-02-18T17:59:34", "id": 1, "name": "John", "age": 60, "updated_at": "010-02-18T17:59:41"} },
{ "person": { "time": "2010-02-18T17:59:44", "id": 2, "name": "Bob", "age": 50, "updated_at": "010-02-18T17:59:42"} },
{ "person": { "time": "2010-02-18T17:59:54", "id": 3, "name": "Sam", "age": 40, "updated_at": "010-02-18T17:59:43"} }
];
var data = $.map(originalData, function (ele) {
return { id: ele.person.id, name: ele.person.name, age: ele.person.age };
});
Here is a full example that will convert and display the results in HTML.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="Styles/Site.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.6.1.js" type="text/javascript"></script>
<script type="text/javascript">
function CreateTableView(objArray, theme, enableHeader) {
// set optional theme parameter
if (theme === undefined) {
theme = 'mediumTable'; //default theme
}
if (enableHeader === undefined) {
enableHeader = true; //default enable headers
}
// If the returned data is an object do nothing, else try to parse
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '<table class="' + theme + '">';
// table head
if (enableHeader) {
str += '<thead><tr>';
for (var index in array[0]) {
str += '<th scope="col">' + index + '</th>';
}
str += '</tr></thead>';
}
// table body
str += '<tbody>';
for (var i = 0; i < array.length; i++) {
str += (i % 2 == 0) ? '<tr class="alt">' : '<tr>';
for (var index in array[i]) {
str += '<td>' + array[i][index] + '</td>';
}
str += '</tr>';
}
str += '</tbody>'
str += '</table>';
return str;
}
$(document).ready(function () {
var originalData = [
{ "person": { "time": "2010-02-18T17:59:34", "id": 1, "name": "John", "age": 60, "updated_at": "010-02-18T17:59:41"} },
{ "person": { "time": "2010-02-18T17:59:44", "id": 2, "name": "Bob", "age": 50, "updated_at": "010-02-18T17:59:42"} },
{ "person": { "time": "2010-02-18T17:59:54", "id": 3, "name": "Sam", "age": 40, "updated_at": "010-02-18T17:59:43"} }
];
var data = $.map(originalData, function (ele) {
return { id: ele.person.id, name: ele.person.name, age: ele.person.age };
});
$('#results').append(CreateTableView(data, 'lightPro', true));
});
</script>
</head>
<body>
<div id="results" style="width: 500px; margin: 20px auto;">
</div>
You can use jQuery's map function:
var data = $.map(originalData, function(person) {
return { id: person.id, name: person.name, age: person.age };
});
map basically converts each item in an Array, producing a new Array with the modified objects.
$.getJSON("example.json", function(data) {
var name = data.person.name;
var id = data.person.id;
var age = data.person.age;
}
what do exactly mean by a javascript table
u can store in a html table by
var $table = $("<table>
<tr><td>name</td><td>"+name+"</td></tr>
<tr><td>id</td><td>"+id+"</td></tr>
<tr><td>age</td><td>"+age+"</td></tr>
</table>");