I'm new to javascript. I'm developing a web app using javascript and HTML. Here is the code:
<html>
<body>
<table class="table table-striped table-bordered bootstrap-datatable datatable responsive">
<thead>
<tr>
<th>No:</th>
<th>Username</th>
<th>Date registered</th>
<th>Role</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="result11" >
<script type="text/javascript">
Parse.initialize("keyyyyyy", "idddddddddddddddddddddd");
var GameScore = Parse.Object.extend("doctor_details");
var query = new Parse.Query(GameScore);
query.find({
success: function(results) {
for (var i = 0; i < results.length; i++) {
var object = results[i];
var docname = object.get('doc_name');
var date = object.get('doc_regdate');
var k = i + 1;
document.getElementById('result11').innerHTML +="<tr ><td>"+k+"</td><td>"+docname+"</td><td>"+date+"</td><td>doctor</td><td><a class='btn btn-info' href='edit-doctor.php'><i class='glyphicon glyphicon-edit icon-white'></i>Edit</a></td></tr>";
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
</script>
</tbody>
</table>
</body>
</html>
The problem is that I fetch data from parse using javascript parse sdk and render the data to the "tbody" of the data table using inner HTML. Here I get data table showing "no data".Dynamic data displaying only after the data table is displayed.
Pagination,search nothing is working.
I need to know how can I render data when the data table loads.Thanks in advance.
Related
I have a web app, frontend using HTML5, backend using Django.
I the JavaScript part I dynamically create the table header based on user selection in the previous page. But when I tried to set the data-field attribute to load the data dynamically, it could not work. although there's no error in F12 dev tool, the data could not shown in the table (I checked in dev tool, the data-field is there but no data shown in frontend. The first fixed one , course dose shown).
<table id="thisTable" contenteditable='true' class="table table-bordered table-sm" width="100%" cellspacing="0" style="font-size: 1.0rem;"
id="bk-table"
data-toggle="table"
data-toolbar="#toolbar"
data-cookie="true"
data-cookie-id-table="materialId"
data-show-columns="true"
data-show-refresh="true"
data-show-fullscreen="true"
data-show-export="true"
data-height="650"
{# data-sticky-header="true"#}
{# data-sticky-header-offset-left="7em"#}
{# data-sticky-header-offset-right="7em"#}
data-click-to-select="true"
data-id-field="id"
data-show-footer="true"
data-url="/api/materials/"
data-query-params="queryParams"
data-remember-order="true"
data-pagination="true"
data-side-pagination="server"
data-total-field="count"
data-data-field="results">
<thead class="thead-dark" >
<tr contenteditable='true'>
<!--th data-sortable="true" >ID</th-->
<th data-field="courseCode" data-sortable="true" data-formatter="renderCourse"></th>
</tr>
</thead>
</table>
<script>
const eText_iBookStore = ['Course Code', 'Course Material Title', 'eISBN/VBID', 'iSBN']
function queryParams(params) {
params['limit'] = localStorage['Format'];
params['discipline'] = localStorage['discipline'];
params['Add_Information'] = localStorage['Add_Information'];
if (params['Add_Information'] == "eText_iBookStore")
{
//document.getElementsByTagName("th")[0].setAttribute("data-field", "id");
//document.getElementsByTagName("th")[1].setAttribute("data-field", "courseCode");
//document.getElementsByTagName("th")[3].setAttribute("data-field", "book.isbn");
for (i=0;i<eText_iBookStore.length;i++)
{
var tr = document.getElementById('thisTable').tHead.children[0],
th = document.createElement('th');
tr.appendChild(th);
}
$( "table thead tr th" ).each(function( index ) {
$( this ).text(eText_iBookStore[index]);
console.log(eText_iBookStore[index]);
console.log( index + ": " + $( this ).text() );
});
document.getElementsByTagName("th")[2].setAttribute("data-field", "book.title");
} }</script>
The data-field attribute dynamically loaded in js does not work like that added in HTML, (the former could not load data )
the code is working well and adding the attribute but you are creating unnecessary loop inside the loop of eText_iBookStore so i remove .each loop and added the array element directly
because i haven't something like your code inside my localStorage i just set a value to them and created the eText_iBookStore array
function queryParams(params) {
params['limit'] = "data"
params['discipline'] = "data"
params['Add_Information'] = "eText_iBookStore"
var eText_iBookStore = [1,2,3,4]
if (params['Add_Information'] == "eText_iBookStore") {
for (var i = 0;i < eText_iBookStore.length; i++) {
var tr = document.getElementById('thisTable').tHead.children[0],
th = document.createElement('th');
th.innerText = eText_iBookStore[i];
tr.appendChild(th);
}
document.getElementsByTagName("th")[2].setAttribute("data-field", "book.title");
}
}
queryParams({})
I'm trying to populate my bootstrap table (in Database.Master) with data (in DatabaseUI.aspx.cs).
How do I dynamically add rows to the table with Jquery?
Do I have to convert my string to JSON?
I think I have to add another JQuery script in the masterpagefile to append data to the table
$(function() {
$.each(response, function(i, item) {
var $tr = $('<tr>').append(
$('<td>').text(item.UID)
.appendTo('#lblDatabase');
});});
but I'm not sure how to pass to get response in the script to read the string in DatabaseUI.
In Database.Master
<form id="form1" runat="server">
<table class="table" id="lblDatabase">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Pid</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
<asp:Label ID="lblDatabaseValues" runat="server"></asp:Label>
</td>
</tr>
</tbody>
</table>
</form>
Code that gets data from API in DatabaseUI
protected async void GetRequest(string url)
{
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(url))
{
using (HttpContent content = response.Content)
{
Label lblDatabaseValues = (Label)Master.FindControl("lblDatabaseValues");
//lblDatabaseValues.Text = "Values:";
//lblDatabaseValues.Text = "";
string myContent = await content.ReadAsStringAsync();
string[] values = myContent.Split(';');
for (int i = 0; i < values.Length; i++)
{
lblDatabaseValues.Text = lblDatabaseValues.Text + Environment.NewLine + values[i];
}
lblDatabaseValues.Text = lblDatabaseValues.Text.ToString().Replace(Environment.NewLine, "<br />");
}
//response.IsSuccessStatusCode
//response.StatusCode
}
}
}
Basically the question is not much clear. If you are asking about how to loop over the received response from backend and append it to your table then here is the code for you.
<table id="tdUIDs">
</table>
var rows = "";
$.each(response,function(i,item){
rows += "<tr><td>" + item.UID + "</td></tr>"; //your rows get printed here
});
$("#tdUIDs").append(rows);
I hope this is what you are asking for as am not clear with your question.
I am trying to use the esimakin jQuery Pagination plugin to break my table up into multiple pages because it is getting its data from an ever growing database. However my pagination bar does not:
Split table into pages
Change pages when I click next or previous.
Any advice would be much appreciated.
HTML:
<div class="table-responsive">
<div class="form-group pull-right">
<input type="text" id="myInput" onkeyup="filterTable()" class="search form-control" placeholder="Filter Table">
</div>
<div class="form-group pull-left">
Load Selected
</div>
<table id="draftTable" class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th data-field="radio"></th>
<th data-field="bulletin_id">Bulletin ID</th>
<th data-field="event">Event</th>
<th data-field="badge_num">Badge Number</th>
<th data-field="AYEAR">Year</th>
</tr>
<tbody>
</tbody>
</thead>
</table>
</div>
<ul id="pagination" class="pagination-sm pull-right"></ul>
</div>
</div>
JS:
<script>
$(document).ready(function(){
populateTables('S');
});
function populateTables(res){
console.log(res)
$.getJSON("bulletinListJSON.asp", {res:res}, function(data){
}).done(function( data ) {
for (var i=0;i<=data.length;i++){
var draftData = "<tr><td><input type=radio value="+ i + " name=load id=load /></td><td>" + data[i].BULLETIN_ID + "</td><td>" + decodeURIComponent(data[i].EVENT) + "</td><td>" + data[i].BADGE_NUM + "</td><td>" + data[i].AYEAR + "</td></tr>";
$('#draftTable').find('tbody').append(draftData);
}
});
}
function filterTable(event) {
var filter = event.target.value.toUpperCase();
var rows = document.querySelector("#draftTable tbody").rows;
for (var i = 0; i < rows.length; i++) {
var firstCol = rows[i].cells[1].textContent.toUpperCase();
var secondCol = rows[i].cells[2].textContent.toUpperCase();
var thirdCol = rows[i].cells[3].textContent.toUpperCase();
var fourthCol = rows[i].cells[4].textContent.toUpperCase();
if (firstCol.indexOf(filter) > -1 || secondCol.indexOf(filter) > -1 || thirdCol.indexOf(filter) > -1 || fourthCol.indexOf(filter) > -1) {
rows[i].style.display = "";
} else {
rows[i].style.display = "none";
}
}
}
document.querySelector('#myInput').addEventListener('keyup', filterTable, false);
$("#draftTable tr").click(function(){
$(this).addClass('selected').siblings().removeClass('selected');
var value=$(this).find('td:second').html();
alert(value);
});
$('.ok').on('click', function(e){
alert($("#table tr.selected td:first").html());
});
//Pagination
$('#pagination').twbsPagination({
totalPages: 35,
visiblePages: 7,
items: 20,
itemOnPage: 8,
});
</script>
search in google:
jq dataTables
Wery nice table.
Search, Download (Excel, word, pdf), order column, server side or cliend side run, more more....
İm use this. 15 million rows.
The twbs-pagination plugin provides an onPageClick callback option; you'll need to implement that.
You could also dynamically set the total number of page based on the length of the response data.
A snippet from a simple gist based on your situation.
function setContent( page ) {
// generate markup to display
$('#page-content').html(data[page]);
}
$('#pagination').twbsPagination({
totalPages: data.length, // from $.ajax response
visiblePages: 7,
onPageClick: function (event, page) {
setContent(page);
}
});
I have a jsp with a bootstrap wizard, like this:
http://s3.amazonaws.com/creativetim_bucket/products/22/original/wizard_template.png?1407329794
With this wizard, I can add the employees element collected in Javascript array (I also use AngularJS).
After that, in the last step of wizard there is the summary of the employees shown in a table.
For each row of the table, I have been added an href link to delete the current employee element. This href link calls a function managed by AngularJS.
Ok, it work. But, after the deletion, the table is not refresh. And the deleted element is present in table yet, but not in array.
So, how can I refresh the table?
Here's the code of the table:
<table class="table table-bordered table-hover table-condensed">
<thead>
<tr>
<td>#</td>
<td>Nome</td>
<td>Cognome</td>
<td>Matricola</td>
</tr>
</thead>
<tr ng-repeat="employee in listaDipendenti track by $index">
<td>{{$index + 1}}</td>
<td>{{employee.nome}}</td>
<td>{{employee.cognome}}</td>
<td>{{employee.matricola}}</td>
<td><a ng-click="DeleteEmployees($index)" href="#" class="btn btn-simple btn-xs" role="button" style="color: green">Delete</a></td>
</tr>
</table>
Here's the code in JS:
//Classe di tipo Employee
function Employee(nome, cognome, matricola) {
this.nome = nome;
this.cognome = cognome;
this.matricola = matricola;
}
var listEmployees = [];
var nDip = 0;
function Controller($scope) {
$scope.DeleteEmployees = function (n) {
if (n > -1) {
listEmployees.splice(n, 1);
}
};
}
for #charlietfl
It's not right, look the function used to add an employee in JS array.
$scope.AddInList = function () {
var nome = $("#nome").val();
var cognome = $("#cognome").val();
var matricola = $("#matricola").val();
$("#nome").val("");
$("#cognome").val("");
$("#matricola").val("");
nDip = nDip + 1;
listEmployees.push(new Employee(nome, cognome, matricola));
$("#cont").text(nDip);
$scope.listaDipendenti = JSON.parse(JSON.stringify(listEmployees));
};
My ajax script sends json objects to browser but the table is unable to load the json object.
My Ajax script:
$.ajax({
type : "POST",
url : "getLabels.jsp",
data : "mailingID=" + selectedValue, // posCodeSelected
success : function(data) {
response = $.parseJSON(data);// this statement sends data succesfully to browser
},
error : function(response) {
var responseTextObject = jQuery.parseJSON(response.responseText);
}
});
This is my bootstrap table embedded into my jsp page.
<table data-height="299" data-show-refresh="true" data-show-toggle="true" data-show-columns="true" data-search="true" data-select-item-name="toolbar1">
<thead>
<tr>
<th data-field="rowNumber" >ID</th>
<th data-field="firstname" >first name</th>
<th data-field="lastname" >last name</th>
<th data-field="organization" >organization</th>
<th data-field="city" >city</th>
<th data-field="state" >state</th>
</tr>
</thead>
</table>
Just to let you guys now this is my json response in browser:
{"rowNumber":1,"mailingID":3,"firstname":"Brian","lastname":"Fairhurst","organization":"Florida State University","city":"Tallahassee","state":"FL"}
You have to add a new row with the json object returned:
//you need to set id="tbl" to your table on the html
var table = document.getElementById("tbl");
var row = table.insertRow(table.rows.length); //insert a new row
// insert new cells with info
cells = [];
for(var i = 0;i < 6;i++){
cells[i] = row.insertCell(i);
}
// add the information store in json object
cells[0].innerHTML = response.rowNumber;
cells[0].innerHTML = response.firstname;
cells[0].innerHTML = response.lastname;
cells[0].innerHTML = response.organization;
cells[0].innerHTML = response.city;
cells[0].innerHTML = response.state;
The problem is that the HTML table isn't being populated with the data in response. Adding the data-url attribute to your HTML table should work.
So, instead of:
<table data-height="299" data-show-refresh="true" ...>
<thead>
...
You'll want to do:
<table data-height="299" data-show-refresh="true" data-url="response"...>
<thead>
...