Creating a dynamic table where pageList has variable length with each response. Attempting to apply Bootstrap's table-striped class however this styling seems to not work. Any thoughts? I've looked at other examples but they don't seem to match what is going on here :
<div class="container-fluid">
<div class="table-responsive">
<table class="table table-outline table-striped table-hover">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
<th>Email</th>
</tr>
</thead>
<tbody style="background-color: white; ">
<tr>
<td class="name"></td>
<td class="address"></td>
<td class="email"></td>
</tr>
</tbody>
</table>
</div>
</div>
/////
for (r = 0; r < pageList.length; r++) {
$('.name').append("<br>" + fullName + "<br>");
$('.address').append("<br>" + homeAddress + "<br>");
$('.email').append("<br>" + "$" + personalEmail + "<br>");
}
So there appear to be a few issues with your example code.
The main issue is that your for loop does not add any rows to the table. Each iteration through the loop should add a <tr>, a child <td> and the data in the table cell.
The background-color: white; is unnecessary
Your for loop is iterating over pageList. However, it does not appear to actually assign the next element in the pageList to a variable. Presumably each element is an object containing an object with fields for fullName, homeAddress and personalEmail.
Based on this assumption, you can use code similar to the example below to create a dynamic table.
var pageList = [{
fullName: "John Doe",
homeAddress: "13 Home St",
personalEmail: "you#mail.com"
},
{
fullName: "Jane Doe",
homeAddress: "55 Work St",
personalEmail: "me#mail.com"
}
];
for (r = 0; r < pageList.length; r++) {
var e = pageList[r];
var tbody = $("#theTable tbody");
tbody.append("<tr><td>" + e.fullName + "</td><td>" + e.homeAddress + "</td><td>" + e.personalEmail + "</td></tr>");
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container-fluid">
<div class="table-responsive">
<table id="theTable" class="table table-outline table-striped table-hover">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
<th>Email</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
In your example, you're only appending the new values to the existing row in the table. Instead, you should insert a new row for each item.
Something like:
var pageList = [
{
fullName: 'TestName1',
homeAddress: 'TestAddress1',
personalEmail: 'TestEmail1'
},
{
fullName: 'TestName2',
homeAddress: 'TestAddress2',
personalEmail: 'TestEmail2'
}
];
var table = document.getElementsByTagName("table")[0].getElementsByTagName("tbody")[0];
for(const item of pageList) {
var row = table.insertRow(0);
var nameCell = row.insertCell(0);
var addressCell = row.insertCell(1);
var emailCell = row.insertCell(2);
nameCell.className = 'name';
addressCell.className = 'address';
emailCell.className = 'email';
nameCell.innerText = item.fullName;
addressCell.innerText = item.homeAddress;
emailCell.innerText = item.personalEmail;
}
Related
In my scenario i have a table which inputs data from user and save the table rows first in json array then pass this array to MVC controller using ajax.
The data in table (eg name eid student id )are fill from server side from controller using jquery then user have to provide marks against each student.then the table data along with marks pass from view to controller using ajax.
Scenario for Problem:
if user fill some rows not all ones then only filled rows data should be inserted in json array.How can I achieve this using Jquery . first check if the row is filled then add that row data in array
#Html.DropDownList("ClarderSousSecteurID", "--- Tous ---")
<input id="date" value='#DateTime.Now.ToString(" dd/mm/yyyy")' />
<input id="date" type="hidden" value='#ViewBag.P_No' />
<table id="tableId" class="table table-bordered table-condensed table-hover table-striped">
<thead>
<tr>
<th>Student_id</th>
<th>Name</th>
<th>Did he perform well</th>
<th>According to Criteria</th>
<th>To the point</th>
<th>EID</th>
</tr>
</thead>
<tbody></tbody>
</table>
<input type="submit" id="savebtn" class="btn btn-success" value="Save" style="display:none;" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script type="text/javascript">
var date;
var val;
$("#ClarderSousSecteurID").change(function () {
val = $("#ClarderSousSecteurID").val();
$("#tableId > tbody").empty();
date = $("#date").val();
$("#savebtn").show();
alert("selected=" + val + date)
var data = JSON.stringify({
'val': val
});
$.ajax({
type: "POST",
url: "/judge_dashboard/Getstudents",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var tr;
//Append each row to html table
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].stud_id + "</td>");
tr.append("<td>" + data[i].stud_name + "</td>");
tr.append("<td><input id='one'></td>");
tr.append("<td><input id='two'></td>");
tr.append("<td><input id='three'></td>");
tr.append("<td>" + data[i].E_id + "</td>");
$('table').append(tr);
}
alert(r + "=== record(s) inserted." + data);
}
});
});
$("body").on("click", "#savebtn", function () {
var marks = new Array();
$("#tableId TBODY TR").each(function () {
{
alert("filled row")
var row = $(this);
var details = {};
details.DATE = date;
details.One_marks = row.find("TD").eq(2).html();
details.Two_marks = row.find("TD").eq(3).html();
details.Three_marks = row.find("TD").eq(4).html();
details.Eid = row.find("TD").eq(5).html();
details.Contest_id = val;
marks.push(details);
}
});
//Send the JSON array to Controller using AJAX.\
var data = JSON.stringify({
'judges': marks,
'val': val
});
alert(data);
$.ajax({
type: "POST",
url: "/Contest_judge/InsertJudge",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + "=== record(s) inserted." + data);
}
});
});
</script>
Note: order of data in Json Array should be following
Date,one(or One_marks),two(or Two_marks),three(or Three_marks),Eid
because I have to insert the whole row as a object in database from controller so the order of column elements for each row in json array matter
Based on your sample, I wasn't sure if you were labeling your inputs, so this example has no-name inputs, but inherits their context from the header row.
$("body").on("click", "#savebtn", function() {
var marks = new Array();
$("#tableId tbody tr").each(function() {
let mark = {
Eid: $(this).find('td').eq(5).text(),
DATE: 'date',
Contest_id: 'val'
}
let empty = true;
$(this).find('td').each(function(i, o) {
if ($(o).find('input').length > 0 && $(o).find('input').eq(0).val().trim() !== '') {
mark[$("#tableId thead th").eq(i).text()] = $(o).find('input').eq(0).val();
empty = false;
}
})
if (!empty) marks.push(mark);
});
//Send the JSON array to Controller using AJAX.\
var data = JSON.stringify({
'judges': marks,
'val': 'val'
});
console.log(data)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tableId" class="table table-bordered table-condensed table-hover table-striped">
<thead>
<tr>
<th>Student_id</th>
<th>Name</th>
<th>Did he perform well</th>
<th>According to Criteria</th>
<th>To the point</th>
<th>EID</th>
</tr>
</thead>
<tbody>
<tr>
<td>123</td>
<td>abc</td>
<td><input/></td>
<td><input /></td>
<td><input /></td>
<td>111</td>
</tr>
<tr>
<td>223</td>
<td>abc</td>
<td><input /></td>
<td><input /></td>
<td><input /></td>
<td>222</td>
</tr>
<tr>
<td>323</td>
<td>abc</td>
<td><input /></td>
<td><input /></td>
<td><input /></td>
<td>333</td>
</tr>
</tbody>
</table>
<button id='savebtn'>save</button>
My post data is being displayed on the console. But the html table shows undefined
The image below shows the problem.
My Jquery Code:
$(document).ready(function(){
//Loading all posts
var loadposts=function(){
$.ajax({
url:"http://localhost:12091/api/post/",
crossdomain: true,
method:"GET",
complete:function(xmlhttp,status){
if(xmlhttp.status==200)
{
var data=xmlhttp.responseJSON;
$("#msg").html(data[0]);
console.log(data[0]);
var str='';
for (var i = 0; i < data.length; i++) {
str += "<tr>";
str += "<td>"+data[i].UserId+"</td>";
str += "<td>"+data[i].PostId+"</td>";
str += "<td>"+data[i].Post1+"</td>";
str += "<td><button class='btn btn-danger' onclick=\"deletepost("+data[i].PostId+")\">Delete</button></td>";
str += "<td><button class='btn btn-info' onclick=\"editpost()\">Edit</button></td>";
str += "</tr>";
}
$("#show__posts tbody").html(str);
}
else
{
$("#msg").html(xmlhttp.status+":"+xmlhttp.statusText);
}
}
});
}
loadposts();
});
The html table:
<div class="container">
<p id="msg"></p>
<table class="table table-striped" border="1" id="show__posts" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th>User Id</th>
<th>Post Id</th>
<th>Post</th>
<th>Delete</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
What am I doing wrong?
Probably irrelevant but i'm using asp.net web api in the backend
JavaScript doesn't have a .length property for objects. If you want to work it out, you have to use Object.keys(data).length instead.
I need to put each element of an array into the corresponding table column, but currently it just puts the entire array into the first column. I feel like this solution will be a simple nested for loop but I am unsure, would appreciate any help. Thanks!
index.html
<div id="PersonContainer" class="DBcontainer">
<form action='/addPerson' method="GET"></form>
<table class="center" id="personTable">
<caption>People Table</caption>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Hooks ID</th>
<th>Soft Plastic ID</th>
<th>Rods ID</th>
<th>Number of Hooks</th>
<th>Number of Soft Plastics</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button type="button" onclick="displayPerson()">Click Me</button>
</form>
</div>
index.html script
<script>
function displayPerson() {
// console.log('test');
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var person = xhttp.responseText;
var element = document.getElementById("personTable");
var result = JSON.parse(person).map((item) => Object.values(item));
for(i = 0; i < result.length; i++){
element.innerHTML += '<td>' + result[i] + '</td>';
}
}
};
xhttp.open("GET", "/AddPerson", true);
xhttp.send();
}
</script>
the xhttp.responseText
[{"id":1,"first_name":"Tyler","last_name":"Marlow","hooks_id":1,"sp_id":1,"rods_id":1,"num_hooks":10,"num_sp":30},{"id":2,"first_name":"Jon","last_name":"Marlow","hooks_id":2,"sp_id":1,"rods_id":1,"num_hooks":50,"num_sp":200}]
Also note that when another person is added I would like another row to be added to the table with the values in proper columns
Putting a new row onto a table in JavaScript can be done with the insertRow function and adding a cell to a row can be done with the insertCell function.
So in your code (depending on exactly what your parsed JSON looks like) in your for loop you are going to do something like:
row = element.insertRow(i); // add a new row to your table
row.insertCell(0).innerHTML =
row.insertCell(1).innerHTML =
and so on
....
But of course you'd put the insertCell line into a for loop as well.
function displayPerson() {
// console.log('test');
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var person = xhttp.responseText;
var element = document.getElementById("personTable");
var rows = ``;
JSON.parse(person).forEach(item => {
var row = `<tr>`;
row += `<td>${item.first_name}</td>`;
row += `<td>${item.last_name}</td>`;
row += `<td>${item.hooks_id}</td>`;
row += `<td>${item.sp_id}</td>`;
row += `<td>${item.rods_id}</td>`;
row += `<td>${item.num_hooks}</td>`;
row += `<td>${item.num_sp}</td>`;
row += `</tr>`;
rows += row;
});
element.innerHTML = rows;
}
};
xhttp.open("GET", "/AddPerson", true);
xhttp.send();
}
<div id="PersonContainer" class="DBcontainer">
<form action='/addPerson' method="GET">
<table class="center">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Hooks ID</th>
<th>Soft Plastic ID</th>
<th>Rods ID</th>
<th>Number of Hooks</th>
<th>Number of Soft Plastics</th>
</tr>
<thead>
<tbody id="personTable">
</tbody>
</table>
<button type="button" onclick="displayPerson()">Click Me</button>
</form>
</div>
In an HTML table, I have to obtain the maximum value of a column, then its position to find other information in another columns in the same row. Currently, I can find the maximum value but not its position in the column.
I have a classic table ans code like below:
<body>
<table id="tableau">
<thead>
<tr>
<th>#</th>
<th>Firstname</th>
<th>Lastname</th>
<th>City</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>José</td>
<td>Maire</td>
<td>Paris</td>
<td>1000</td>
</tr>
<tr>
<td>2</td>
<td>Lilianne</td>
<td>Maire</td>
<td>Paris</td>
<td>1234</td>
</tr>
<tr>
<td>3</td>
<td>Raymond</td>
<td>Fourbe</td>
<td>Bruxelles</td>
<td>123</td>
</tr>
<tr>
<td>4</td>
<td>Huguette</td>
<td>Fourbe</td>
<td>Bruxelles</td>
<td>129099</td>
</tr>
</tbody>
</table>
<button type="buttonmax" id="Score maximum" class="btn btn-info">Afficher le Score maximum</button>
<script>
var myArray = new Array();
$(document).ready(function()
{
$("#tableau tr td:nth-child(5)").each(function(i){
myArray.push($(this).text());
});
document.getElementById("Score maximum").onclick = function(){
var max = Math.max.apply(Math, $('td:nth-child(5)').map(function(i,elem){
return Number($(elem).text());
}));
alert(max);}
});
</script>
</body>
In my opinion, I have to find the index of the maximum value to display the the Firstname and Lastname of the person who realized this value, situated in the same row but in other columns.
Do you think it's the best way to do this?
I tried diverse codes to obtain the index of max but none worked.
Could you please help me to obtain the index and find the person who realized the best score?
This would be a way to achieve this (altough it is not very performant because it would overwrite the whole object if the current checked value is higher than the previous one).
PLEASE NOTE: I changed your id to "scoremaximum" because you really shouldn't have whitespaces in your id selector.
var max = {
score: 0,
id: 0,
firstname: '',
lastname: '',
city: ''
};
$("#tableau tr td:nth-child(5)").each(function(index, elem) {
var current = parseFloat($(elem).text());
if(current > max.score) {
max.score = current;
max.id = $("#tableau tr td:nth-child(1)")[index].textContent;
max.firstname = $("#tableau tr td:nth-child(2)")[index].textContent;
max.lastname = $("#tableau tr td:nth-child(3)")[index].textContent;
max.city = $("#tableau tr td:nth-child(4)")[index].textContent;
}
});
$('#scoremaximum').on('click', function() {
alert("score: " + max.score + ", id: " + max.id + ", firstname: " + max.firstname + ", lastname " + max.lastname + ", city: " + max.city);
});
You could increase the performance a little bit if you would add another property to the object that keeps track of the index outside of the loop and update it accordingly to the max.score. Then you could run a callback function after the loop has finished and pass it the max.index. That would look like this:
var max = {
score: 0,
index: 0,
id: 0,
firstname: '',
lastname: '',
city: ''
};
$("#tableau tr td:nth-child(5)").each(function(index, elem) {
var current = parseFloat($(elem).text());
if(current > max.score) {
max.score = current;
max.index = index;
}
return callback(max.index);
});
function callback(index) {
max.id = $("#tableau tr td:nth-child(1)")[index].textContent;
max.firstname = $("#tableau tr td:nth-child(2)")[index].textContent;
max.lastname = $("#tableau tr td:nth-child(3)")[index].textContent;
max.city = $("#tableau tr td:nth-child(4)")[index].textContent;
}
$('#scoremaximum').on('click', function() {
alert("score: " + max.score + ", id: " + max.id + ", firstname: " + max.firstname + ", lastname " + max.lastname + ", city: " + max.city);
});
Codepen: https://codepen.io/anon/pen/KYyyKV
I have trying to load html page in to div in another view using jquery load.
$("#sideMenuCustomerDivition").click(function (e) {
e.preventDefault();
$('#subContents').load('Main/Customer');
});
This is my html
<div class="contents" id="subContents">
</div>
<!-- CDN JavaScript Links-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<!-- end-->
I have put html table in my other view and trying to load data to that table using angular. But my table display like this
This is my javascript for loaded view
angular.module('myApp', ['smart-table']).controller('safeCtrl', ['$scope', function ($scope) {
var firstnames = ['Laurent', 'Blandine', 'Olivier', 'Max'];
var lastnames = ['Renard', 'Faivre', 'Frere', 'Eponge'];
var dates = ['1987-05-21', '1987-04-25', '1955-08-27', '1966-06-06'];
var id = 1;
function generateRandomItem(id) {
var firstname = firstnames[Math.floor(Math.random() * 3)];
var lastname = lastnames[Math.floor(Math.random() * 3)];
var birthdate = dates[Math.floor(Math.random() * 3)];
var balance = Math.floor(Math.random() * 2000);
return {
id: id,
firstName: firstname,
lastName: lastname,
birthDate: new Date(birthdate),
balance: balance
}
}
$scope.rowCollection = [];
for (id; id < 5; id++) {
$scope.rowCollection.push(generateRandomItem(id));
}
//copy the references (you could clone ie angular.copy but then have to go through a dirty checking for the matches)
$scope.displayedCollection = [].concat($scope.rowCollection);
//add to the real data holder
$scope.addRandomItem = function addRandomItem() {
$scope.rowCollection.push(generateRandomItem(id));
id++;
};
//remove to the real data holder
$scope.removeItem = function removeItem(row) {
var index = $scope.rowCollection.indexOf(row);
if (index !== -1) {
$scope.rowCollection.splice(index, 1);
}
}
}]);
and this is html
<table st-table="rowCollection" class="table table-striped">
<thead>
<tr>
<th>first name</th>
<th>last name</th>
<th>birth date</th>
<th>balance</th>
<th>email</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in rowCollection">
<td>{{row.firstName}}</td>
<td>{{row.lastName}}</td>
<td>{{row.birthDate}}</td>
<td>{{row.balance}}</td>
<td>{{row.email}}</td>
</tr>
</tbody>
</table>
<script src="~/Scripts/CustomerView.js"></script>