$(#id).html(content) function to set content to the next column - javascript

This is my HTML code:
<div class="row margin-top-3">
<div class="col-sm-7">
<h2>NFTs</h2>
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th id = "NFTID">NFT ID</th>
<th id = "NFTNAME">NFT Name</th>
<th id = "NFTCREATOR">Creator</th>
</tr>
</thead>
<tbody id="NFT-rows">
</tbody>
</table>
</div>
</div>
</div>
The following three functions populate the table by column.
The problem is that the third function overwrites the second column instead of the third column.
Also, adding a fourth function will again overwrite the second column.
So, how can I re-write the $(#id).html(content) part to make it populate the next column instead of the second?
setupNFTRows: function() {
console.log("setupNFTrows NFT Array = " + JSON.stringify(NFTs));
console.log("NFT = " + Object.keys(NFTs))
Object.keys(NFTs).forEach(function (NFT) {
console.log("inside setupNFTrows");
$("#NFT-rows").append("<tr><td>" + "NFT_ID_" + NFT + "</td><td id='" + NFTs[NFT] + "'></td></tr>");
});
},
populateNFTNames: function() {
console.log("inside populateNFTNames")
let NFTIDs = Object.keys(NFTs);
console.log("NFTIDs = " + NFTIDs)
for(var i=0; i < NFTIDs.length; i++) {
let nftid = NFTIDs[i];
NFTContract.deployed().then(function(contractInstance) {
contractInstance.getNFTname.call(nftid).then(function(v) {
$("#" + NFTs[nftid]).html(v.toString());
})
})
}
},
populateCreators: function() {
let NFTIDs = Object.keys(NFTs);
for(var i=0; i < NFTIDs.length; i++) {
let nftid = NFTIDs[i];
NFTContract.deployed().then(function(contractInstance) {
contractInstance.getCreator.call(nftid).then(function(v) {
$("#" + NFTs[nftid]).html(v.toString());
})
})
}
},

This is because data tables are populated a row at a time, not a column at a time. The best way to approach this would be to zip your data together into a cohesive set to fill the rows:
const getNFTNames = (id) => {
NFTContract.deployed().then(contractInstance => {
contractInstance.getNFTname.call(nftid).then(v => {
return v.toString();
});
});
};
const getCreators = (id) => {
NFTContract.deployed().then(contractInstance => {
contractInstance.getCreator.call(nftid).then(v => {
return v.toString();
});
});
};
const setupNFTRows = () => {
Object.keys(NFTs).forEach(id => {
$("#NFT-rows").append(
`<tr id='NFT_ID_${id}'>
<td>NFT_ID_${id}</td>
<td>${getNFTNames(id)}</td>
<td>${getCreators(id)}</td>
</tr>`);
});
};

Related

Search still works after deleting a user + cells keep being created without an input

been working on some basic contacts app and got stuck in two places. Cells keep being created in the table even if there's no input (I've tried if statements) + after deleting a contact I can still search for it. How to remove it from the database? Is it possible to make the create button appear after all the fields have input in it? How can I remove the elements from db array after deleting the cells?
let db = [];
let contact = {};
// ADD CONTACT
$(document).ready(function() {
$("#create-contact").on("click", function(event) {
event.preventDefault();
contact.firstName = $('#name').val();
contact.surname = $('#surname').val();
contact.phone = $("#phone").val();
contact.address = $("#address").val();
let row = document.createElement("tr");
$("table").append(row);
let cell1 = document.createElement("td");
let cell2 = document.createElement("td");
let cell3 = document.createElement("td");
let cell4 = document.createElement("td");
let dltBtn = document.createElement("button");
/* ^ https://stackoverflow.com/questions/268490/jquery-document-createelement-equivalent
Fastest method */
$(dltBtn).text("X")
.css("width", "8.5rem")
.css("color", "white")
.css("background-color", "black")
.attr("class", "dltBtn");
$(cell1).html(contact.firstName);
$(cell2).html(contact.surname);
$(cell3).html(contact.phone);
$(cell4).html(contact.address);
row.append(cell1, cell2, cell3, cell4,dltBtn);
db.push(contact.firstName, contact.surname, contact.phone, contact.address);
console.log(db);
$('.dltBtn').on('click', function(event) {
event.preventDefault();
row.remove(dltBtn)
.deleteCell();
});
});
// SEARCH
function search(name) {
for (i = 0; i < db.length; i++) {
if (!isNaN(name) && db[i] === name) {
return db[i-2] + " " + db[i-1] + " " + db[i] + " " + db[i+1];
}
if (db[i].toUpperCase() === name.toUpperCase()) {
return db[i] + " " + db[i+1] + " " + db[i+2] + " " + db[i+3];
}
$("#found").text("User not found!");
}
};
$('.searchbutton').on('click', function(event) {
event.preventDefault();
var findUserName = $('#query').val();
var userFound = search(findUserName);
$("#found").text(userFound);
console.log(db);
});
});
This example might be more complex than you are needing. Consider creating a db Object with built in functions.
$(function() {
var db = {
content: [],
headers: [
"First Name",
"Last Name",
"Phone",
"Address",
" "
],
tableRef: null,
insert: function(row) {
this.content.push(row);
this._drawTable();
},
delete: function(row_id) {
this.content.splice(row_id, 1);
this._drawTable();
},
search: function(term) {
if (term == undefined || term == "") {
return false;
}
var table = $(this.tableRef);
$("tbody tr", table).hide().each(function(i, row) {
if ($("td:eq(0)", row).text().toLowerCase().indexOf(term.toLowerCase()) >= 0) {
$(row).show();
}
});
},
_getContent: function(id) {
this.tableRef = id;
var table = $(id);
var headers = [];
var rows = [];
$("thead th", table).each(function(i, h) {
headers.push($(h).text());
});
this.headers = headers;
$("tbody tr", table).each(function(i, r) {
rows.push({
firstName: $("td:eq(0)", r).text(),
surName: $("td:eq(1)", r).text(),
phone: $("td:eq(2)", r).text(),
address: $("td:eq(3)", r).text()
});
});
this.content = rows;
console.log("Content collected from " + this.tableRef, this.content.length + " rows.");
},
_drawTable: function() {
var table;
if ($(this.tableRef).length) {
table = $(this.tableRef);
$("tbody tr", table).remove();
} else {
this.tableRef = "#contacts";
table = $("<table>", {
id: "contacts"
}).appendTo("body");
$("<thead>").appendTo(table);
$("<tr>").appendTo($("thead", table));
$.each(this.headers, function(i, h) {
$("<th>").html(h).appentTo($("thead > tr", table));
});
$("<tbody>").appendTo(table);
}
var row;
$.each(this.content, function(i, r) {
row = $("<tr>").appendTo($("tbody", table));
$.each(r, function(j, c) {
$("<td>").html(c).appendTo(row);
});
});
console.log("Table Drawn", this.content.length + " rows");
}
};
db._getContent("#contacts");
$("#contacts").on("click", ".dlt-btn", function(e) {
var rId = $(this).closest("tr").index();
if (confirm("Are you sure you wish to delete this entry?")) {
db.delete(rId);
}
});
$("#add_contact_form").submit(function(event) {
event.preventDefault();
var contact = {
firstName: $("input:eq(0)", this).val(),
surName: $("input:eq(1)", this).val(),
phone: $("input:eq(2)", this).val(),
address: $("input:eq(3)", this).val()
};
db.insert(contact);
this.reset();
});
$("#search_contacts").on("input", "input", function() {
if ($(this).val().length >= 1) {
db.search($(this).val());
} else {
$(db.tableRef).find("tbody tr").show();
}
});
});
#add_contact td,
#add_contact input {
width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="search_contacts">
Search: <input type="text">
</form>
<table id="contacts" width="100%">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Phone</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr>
<td>Homer</td>
<td>Simpson</td>
<td>(939)-555-0113</td>
<td>742 Evergreen Terrace</td>
<td><button class="dlt-btn">X</button></td>
</tr>
<tr>
<td>Marge</td>
<td>Simpson</td>
<td>(939)-555-0113</td>
<td>742 Evergreen Terrace</td>
<td><button class="dlt-btn">X</button></td>
</tr>
<tr>
<td>Bart</td>
<td>Simpson</td>
<td>(939)-555-0113</td>
<td>742 Evergreen Terrace</td>
<td><button class="dlt-btn">X</button></td>
</tr>
<tr>
<td>Lisa</td>
<td>Simpson</td>
<td>(939)-555-0113</td>
<td>742 Evergreen Terrace</td>
<td><button class="dlt-btn">X</button></td>
</tr>
<tr>
<td>Maggie</td>
<td>Simpson</td>
<td>(939)-555-0113</td>
<td>742 Evergreen Terrace</td>
<td><button class="dlt-btn">X</button></td>
</tr>
</tbody>
</table>
<form id="add_contact_form">
<table id="add_contact" width="100%">
<tbody>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
<td width="30px"> </td>
</tr>
</tbody>
</table>
<button type="submit" id="create-contact">Create Contact</button>
</form>
There are lots of ways to manage Arrays. Please see:
https://www.w3schools.com/jsref/jsref_push.asp
https://www.w3schools.com/jsref/jsref_splice.asp
https://www.w3schools.com/jsref/jsref_indexof_array.asp
Once you adjust the Array you need to either redraw the table or perform the same function to the Table element.
Searching, or in this case, filtering, can be done in a lot of ways too. This is a pretty basic example. You can look at other options if you like.

Jquery: I want to add data to a simple html table column wise

I have 3 JavaScript objects, each of which contain one column data (It has 8 entries). I want to add this data to a html table. I am able to retrieve the column data using nth child but not insert.
code snippet:
countNovels = {
Ramesh: 5,
Kumar: 10,
Sameera: 15,
}
countTales = {
Ramesh: 2,
Kumar: 6,
Sameera: 8,
}
<table id="Summary" cellspacing="0">
<tr>
<th >Name</th>
<th >No. of Novels</th>
<th >No. of Fairytales</th>
<th >Total</th>
</tr>
<tbody></tbody>
</table>
var col = "<td style=\"max-width : 40px\">" + countNovels.Ramesh + "</td><td style=\"max-width : 40px\">" + countNovels.Kumar + "</td><td style=\"max-width : 40px\">" + countNovels.Sameera + "</td>";
$('#Summary td:nth-child(1)').text(col);
This is not actual code.
I want the output something like this
Please do help.
It was a nice question :)
The snippet I created works with any number of source objects (so any number of columns in the end).
The transformation function is not ideal - it could generate a better return format (so the HTML template generation would be simpler).
const countNovels = {
Ramesh: 5,
Kumar: 10,
Sameera: 15,
}
const countTales = {
Ramesh: 2,
Kumar: 6,
Sameera: 8,
}
// transformation function
const transformObject = (arr) => {
const r = arr.reduce((acc, c) => {
// key - countNovels, countTales
// obj - the source object content
// k1 - the name of the person
// v1 - the value of key-name (e.g. countTales-Ramesh = 2)
const [
[key, obj]
] = Object.entries(c)
Object.entries(obj).forEach(([k1, v1]) => {
if (typeof acc[k1] === 'undefined') acc[k1] = {}
acc[k1][key] = v1
})
return acc
}, {})
return r
}
// running transformation with two objects
const transformed = transformObject([{
countNovels
},
{
countTales
}
])
// just a utility function
const wrapTd = (item) => {
return `<td>${item}</td>`
}
// creating the HTML template
const addToTable = (obj) => {
let html = ''
for (key in obj) {
const total = Object.values(obj[key]).reduce((a, c) => a + c, 0)
// creating the columns for the numbers (including total)
let values = ''
Object.values(obj[key]).forEach(e => {
values += wrapTd(e)
})
values += wrapTd(total)
// adding name and numbers to rows
const template = `
<tr>
${wrapTd(key)}
${values}
</tr>
`
html += template
}
return html
}
// adding HTML string to DOM
document.getElementById('tablebody').innerHTML = addToTable(transformed)
<table id="Summary" cellspacing="0">
<tr>
<th>Name</th>
<th>No. of Novels</th>
<th>No. of Fairytales</th>
<th>Total</th>
</tr>
<tbody id="tablebody"></tbody>
</table>
On page load, grab both the objects iterate over them and add rows to the last of the table.
window.onload = function() {
const countNovels = {
Ramesh: 5,
Kumar: 10,
Sameera: 15,
};
const countTales = {
Ramesh: 2,
Kumar: 6,
Sameera: 8,
};
function renderTable() {
const tableRows = Object.entries(countNovels).reduce((acc, curr, index) => {
const name = (curr[0] || '');
const novels = curr[1];
const tales = countTales[curr[0]];
const total = novels + tales;
acc.push({
name,
novels,
tales,
total
});
return acc;
}, []);
const tableBody = document.querySelector('#Summary');
for (const tableRow of tableRows) {
let newRow = tableBody.insertRow(-1);
Object.values(tableRow).forEach((curr, index) => {
let newCell = newRow.insertCell(index);
let newText = document.createTextNode(curr);
newCell.appendChild(newText);
});
}
}
renderTable();
};
table,
th,
td {
border: 1px solid black;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table id="Summary">
<tr>
<th>Name</th>
<th>No. of Novels</th>
<th>No. of Fairytales</th>
<th>Total</th>
</tr>
<tbody></tbody>
</table>
</body>
</html>

why my when-scrolled not working in following code

I am trying to load data while the user scrolls down the table on the when-scrolled event but that didn't occur during scroll
i have to implement paging mechanism in my following code
stepwise description
when first-time page load then some data will load
then when user scroll down the next batch of data will load from database and it will continue till the user scroll up
app.service("UserService", function ($http) {
this.getAllUserList = function () {
return $http.get("/FarmerRegistermaster/getAllUser");
};
});
app.directive('whenScrolled', function () {
return function (scope, elm, attr) {
var raw = elm[0];
//alert(attr);
elm.bind('scroll', function () {
if (raw.scrollTop + raw.offsetHeight >= raw.scrollHeight) {
scope.$apply(attr.whenScrolled);
}
});
};
});
app.controller('UserCtrl', function ($scope, UserService) {
//GetAll();
$scope.loaderMore = false;
$scope.scrollended = false;
var IsPaging = 0;
var UserID = 1;
var page = 1;
var PageSize = 20;
var inCallback = false;
var totalData = 0;
//******=========Get All Data with Paging=========******
$scope.loadData = function (IsPaging) {
alert("When Scrolled " + IsPaging);
var geturl = '/FarmerRegistermaster/getAllUser';
if (IsPaging === 1) {
//debugger;
IsPaging = 1;
if (page > -1 && !inCallback) {
inCallback = true;
page++;
$scope.loaderMore = true;
$scope.LoadMessage = ' Loading page ' + page + ' of ' + PageSize + ' data...';
$scope.result = "color-green";
var getUser = UserService.getAllUserList();
getUser.then(function (response) {
$scope.UserList = response.data;
}, function () {
$.notify("Error to load data...", "error");
});
var getUser = UserService.getAllUserList();
getUser.then(function (response) {
$scope.UserList.push(response.data);
}, function () {
$.notify("Error to load data...", "error");
});
}
} //unlimited load data while scroll
else {
//debugger;
IsPaging = 0;
$scope.loaderMore = true;
$scope.LoadMessage = 'Loading page ' + page + ' of ' + PageSize + ' data...';
$scope.result = "color-green";
var getUser = UserService.getAllUserList();
getUser.then(function (response) {
$scope.UserList = response.data;
}, function () {
$.notify("Error to load data...", "error");
});
} //default load data while pageload
};
$scope.loadData();
});
<div ng-controller="UserCtrl" class="panel panel-headline">
<section class="panel">
<header class="panel-heading">
<center><b>User List</b></center>
</header>
<div class="panel-body">
<div class="box box-primary box-body table-responsive widget-content content_scroll"
when-scrolled="loadData(1)">
<table class=" table table-striped table-bordered " cellspacing=" 0">
<thead>
<tr>
<th>ID</th>
<th>USER NAME</th>
<th>MOBILE NO</th>
<th>EMAIL</th>
<th>REG DATE</th>
<th>STATUS</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in UserList >
<td>{{user.FARMER_ID}}</td>
<td>{{user.FARMER_NAME}}</td>
<td>{{user.MOBILE_NO}}</td>
<td>{{user.EMAIL_ID}}</td>
<td>{{user.REG_DATE | jsonDate}}</td>
<td>
{{user.STATUS}}
</td>
<td>
</td>
</tr>
</tbody>
</table>
<div class="loadmore">
<div ng-show="loaderMore" ng-class="result">
<imgsrc ="~/Areas/Crm/Content/img/ng-loader.gif" />{{LoadMessage}}
</div>
<div ng-show="scrollended" ng-class="result">
{{LoadMessage}}
</div>
</div>
</div>
</div>
</section>
</div>
<link href="//cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap.min.css" rel="stylesheet" />
#section Scripts{
<script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="~/AngularJS/DateFilter.js"></script>
<script src="~/AngularJS/UserCtrl.js"></script>
}
<script>
$(document).ready(function () {
$('#dataTable').DataTable({
"paging": true,
"ordering": true,
"info": true
});
});
</script>
when the user scrolled then the reloadData method should be called every time and data is to be fetched from the database

How to show data from a database in my table from my website?

I have a database that I want to access to display my product data, in this case the ItemCode and ItemName.
the connections are all correct and the functional, my problems is the loop and show the data in the table that I have in the html file.
let ctrl = {
showDados: function(r) {
/*dados[3].ItemCode;*/
let dados = JSON.parse(r.responseText);
let cod = dados.ItemCode;
let name = dados.ItemName;
let text = "";
let i;
for (i = 0; i < cod.length; i++) {
text += cod[i] + "<br>";
}
document.getElementById("cod").innerHTML = text;
for (i = 0; i < name.length; i++) {
text += name[i] + "<br>";
}
document.getElementById("name").innerHTML = text;
},
init: function() {
util.ajax(settings.serviceAddress + "OITM", ctrl.showDados);
}
};
$(document).ready(function() {
ctrl.init();
});
<div class="container">
<table class="table table-hover">
<thead>
<tr>
<th>Código</th>
<th>Nome</th>
</tr>
</thead>
<tbody>
<tr>
<td id="cod">FSE0204</td>
<td id="name">25130101_Loc.Finaneira - BCP- CT 400105814</td>
</tr>
<tr>
<td>FSE0205</td>
<td>25130201_Loc.Finaneira - Totta- CT 195649</td>
</tr>
</tbody>
</table>
</div>

jQuery create tables from JSON and group in expandable rows

I want to create a nested table with data from JSON file. here I use an array of object to simulate the back end:
var response = [
{
"mezzo":"fiat punto",
"tipologia":"auto",
"id":"1"
},
{
"mezzo":"fiat punto",
"tipologia":"auto",
"id":"2"
},
{
"mezzo":"fiat punto",
"tipologia":"auto",
"id":"3"
},
{
"mezzo":"alfa giulia",
"tipologia":"auto",
"id":"1"
},
{
"mezzo":"alfa giulia",
"tipologia":"auto",
"id":"2"
},
{
"mezzo":"fiat punto",
"tipologia":"auto",
"id":"4"
},
{
"mezzo":"alfa giulia",
"tipologia":"auto",
"id":"3"
}
];
I want to group my result table using the "mezzo" field, so I try sorting the array:
response.sort(function(a,b){
var mezzoA = a.mezzo.toLowerCase();
var mezzoB = b.mezzo.toLowerCase();
if (mezzoA > mezzoB) {
return -1;
}
if (mezzoA < mezzoB) {
return 1;
}
return 0;
});
now the jQuery code: I try to create elements and append to the DOM using .each() loop. the commented code works with hardcoded demo, but by now I have to group the rows matching the "mezzo" field in a single expandable row:
$(function () {
var parentFrag = document.createDocumentFragment();
$.each(response, function(i, item) {
var parentTr = document.createElement('tr');
var parentTd = '<td>></td><td>' + item.mezzo + '</td><td>' + item.tipologia + '</td><td>' + item.id +'</td>';
parentTr.innerHTML = parentTd;
parentFrag.appendChild(parentTr);
})
var parentTable = $('.parent');
parentTable[0].appendChild(parentFrag);
// Expand-Collapse details table
// $('table table').hide();
// $('td > a').on('click', function (e) {
// e.preventDefault();
// $(this).closest('tr').next().find('table:first').toggle();
// });
});
This is my html file:
<table border="1">
<thead>
<tr>
<td></td>
<td>Mezzo</td>
<td>Tipologia</td>
<td>ID</td>
</tr>
</thead>
<tbody class="parent">
</tbody>
</table>

Categories

Resources