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.
Related
Output
What I want is in this case there are 2 times Demo is being printed, if this column has same name then it should be rowspan. My data is bein fetched from sql and I have displayed on webpage using populate method and forEach(). This is my code.
function populateSubjectData(subjectDetail){
let table = `<form id="addExamSubjectForm" method="POST" enctype="multipart/form-data" action="javascript:;" autocomplete="off">
<table class="table table-bordered" id="addExamSubject">`;
let header = `<tr>
<th>Sr. No.</th>
<th>Subject Name</th>
<th>Sub Subject Name</th>
</tr>`;
let body = "";
subjectDetail.forEach(function(subjectDetailObj, key){
if(key == 0){
console.log("1");
}
var prev = key;
console.log(prev);
var curr = key+1;
console.log(curr);
if(subjectDetail[prev].name === subjectDetail[curr].name){
console.log("error");
}
else{
console.log(subjectDetail[curr].name);
}
body +=`<tr>
<td>${key + 1}</td>
<td>${subjectDetailObj.name}</td>
<td>${subjectDetailObj.subSubjectName}</td>
</tr>`;
});
$('#subjectTable').html(table + header + body);
}
my suggest is to :
structure the fetched data in the server side by grouping them
by columns name, so you will get some thing like that :
PARENT 1
|_CHILD1
|_CHILD2
PARENT 2
|_CHILD1
|_CHILD2
|_CHILD3
in the client side ( javascript ) by knowing the number of childs
in the current object you can make a rowspan in case it has more
than one CHILD or not.
Hope that can be helpful for you.
I want to filter out table before loading it to reduce it's size that it would load faster, when its loaded i would like to let user to filter it. I am using public CDN script for filter part, but it does not work on content which is injected to . It only works if whole table is loaded together with page.. what i'am doing wrong?
Jsfilter: <script type="text/javascript" language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/tablefilter/2.5.0/tablefilter.js"></script>
DetailedRport.html
//this function called on button click it gets user and date to resize data set
<script type="text/javascript">
function myFunction() {
var y = document.getElementById("month-input").value;
var z = document.getElementById("email2").value;
//here is called server side script
google.script.run.withSuccessHandler(onSuccess).functionToRunOnFormSubmit(y, z);
}
//Resized data set gets injected to tbody
function onSuccess(c){
var table=toHTMLTable(c);
document.getElementById('myOutput1').innerHTML = table;
}
//Array to HTML table
function toHTMLTable(a) {
var content = a.map(function(row, i) {
var rowHTML = row.map(function (col) {
return "<td>" + col + "</td>";
}).join("");
return "<tr>" + rowHTML + "</tr>";
}).join("");
return content;
}
</script>
//user selects criteria for data table
<b> Report for:</b>
<select value="" name="email2" id="email2" width="300" autofocus="autofocus" autocorrect="off" autocomplete="off">
<?!= myEmails(); ?>
</select>
<b>Pick Period :</b>
<select name="Student" id="month-input" autofocus="autofocus" autocorrect="off" autocomplete="off">
<?!= myDates(); ?>
</select>
//On click table is loaded based on selection
<input type="button" value="Load Data" class="loadbutton" onclick="myFunction();" >
<br><br>
//Js tablefilter which should work but does not if table is injected
<table id="table1"class="mytable TF" cellspacing="0" cellpadding="0">
<thead>
<tr class="header">
<th style="width:5%;">TASK</th>
<th style="width:20%;">PROJECT</th>
<th style="width:30%;">DATE</th>
<th style="width:10%;">TIME SPENT</th>
<th style="width:10%;">WORDCOUNT</th>
<th style="width:10%;">SPEED</th>
</tr>
</thead>
//Where data table is injected
<tbody id="myOutput1">
</tbody>
</table>
//Setting Js tablefilter source http://tablefilter.free.fr/
<script language="javascript" type="text/javascript">
var tf = setFilterGrid("table1");
</script>
server.gs
// here data set gets filtered based on users selection and is sent back
// Using ArrayLib library
function functionToRunOnFormSubmit(y,z) {
var ss = SpreadsheetApp.openById(id);
var ActiveSheet = ss.getSheetByName("TogglMap");
var StartRow = 2;
var RowRange = ActiveSheet.getLastRow() - StartRow + 1;
var EMWholeRange = ActiveSheet.getRange(StartRow,2,RowRange,13);
var AllValues = EMWholeRange.getDisplayValues();
var dat = y +'-01'
var removeCol = function(arr, colIndex, colIndex2) {
for (var i = 0; i < arr.length; i++) {
var row = arr[i];
row.splice(colIndex, colIndex2);
}
}
removeCol(AllValues, 5 , 6);
var filteredArr1 = ArrayLib.filterByText(AllValues, 1, z)
var filteredArr2 = ArrayLib.filterByText(filteredArr1, 3, dat)
removeCol(filteredArr2, 1 ,1);
Logger.log(AllValues)
return filteredArr2
};
My goal is working JS filter
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.
My MVC Controller passes a Model to view in the following form
public class LibaryModel
{
public int LibaryId { get; set; }
public string[] Books { get; set; }
}
This is my LibraryView.cshtml
#model IEnumerable<LibaryModel>
<table id="myTable" class="table-bordered">
<thead>
<tr>
<th>Libary Id</th>
</tr>
</thead>
<tbody>
#foreach (var library in Model)
{
<tr>
<td>#library.LibaryId</td>
</tr>
}
</tbody>
</table>
Now, On clicking the library id, I need to show another div with the list of books in that library. I am able to get the row number and column number of click event, but I am not able to figure a way to get the list of books in the libary from jQuery. Is there any pattern to solve this?
$("#myTable td").on('click', function () {
var column_num = parseInt($(this).index()) + 1;
var row_num = parseInt($(this).parent().index()) + 1;
});
I would suggest using the LibraryId in a function on a click event in your td.
foreach (var library in Model)
{
<tr>
<td onclick="getHiddens(#library.LibraryId)">#library.LibaryId</td>
</tr>
}
And give your books' hidden inputs a class that contains its library's LibraryId
for (var i = 0; i < library.Books.Length; i++)
{
<input type="hidden" class="book#library.LibraryId" value="#library.Books[i]" />
}
And then sending that LibraryId into a function as an argument that gets all matching inputs by class, and does something with the input's value, like for this example, loading it into a div.
var getHiddens = function (libraryId) {
var books = document.getElementsByClassName("book" + libraryId);
var bookDiv = document.getElementById("bookDiv");
bookDiv.innerHTML = "<ul>";
for (var i = 0; i < books.length; i++) {
bookDiv.innerHTML += "<li>" + books[i].value + "</li>";
}
bookDiv.innerHTML += "</ul>";
}
Please check my code .
#foreach (var library in Model)
{
<tr>
<a href="javascript:void(0)"
onclick="GoToInsured('#library.LibaryId');">
</tr>
}
function GoToInsured(LibaryId)
{
//This LibaryId is current selected row ID.You can open new Diva per
LibaryId. You can get Library details as per LibaryId and you can display
that data on Popup or any place you want.
}
Tell me you have any query regarding my code .
Thanks .
I'm not sure if I'm trying to do too much here, but here is the scenario. I have an asp.net mvc page that, on the first time loading, returns a table of data in a view using the standard foreach mechanisms in the mvc framework. If the user has javascript enabled, I want to use knockout to update the table going forward. Is there a way to have knockout read the data from the dom table and use that data as the initial observable collection. From then on out, I would use knockout and ajax to add, edit, or delete data.
In a nutshell, I need to parse an html table into a knockout observable collection.
I've had a go at coding this up:
Here's the basic markup:
<table id="table" data-bind="template: { name: 'table-template' }">
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
</tr>
</thead>
<tbody>
<tr>
<td>Richard</td>
<td>Willis</td>
</tr>
<tr>
<td>John</td>
<td>Smith</td>
</tr>
</tbody>
</table>
<!-- Here is the template we'll use for re-building the table -->
<script type="text/html" id="table-template">
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
</tr>
</thead>
<tbody data-bind="foreach: data">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: surname"></td>
</tr>
</tbody>
</script>
Javascript:
(function() {
function getTableData() {
// http://johndyer.name/html-table-to-json/
var table = document.getElementById('table');
var data = [];
var headers = [];
for (var i = 0; i < table.rows[0].cells.length; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi, '');
}
// go through cells
for (var i = 1; i < table.rows.length; i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j = 0; j < tableRow.cells.length; j++) {
rowData[headers[j]] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data;
}
var Vm = function () {
this.data = ko.observableArray(getTableData());
};
ko.applyBindings(new Vm(), document.getElementById('table'));
})();
You can extend this concept using the mapping plugin to create observables for each row: http://knockoutjs.com/documentation/plugins-mapping.html
View a demo here: http://jsfiddle.net/CShqK/1/
EDIT: I'm not saying this is the best approach, as it can be costly to traverse a large table to get the data. I would probably just output the JSON in the page as suggested by others in this thread.
How about just feeding your observable array with the data instead of parsing the html table
myArray: ko.observableArray(#Html.Raw(Json.Encode(Model.myTableData)))
If you really need to go the parsing the html way, you can use the following code
var tableData = $('#myTable tr').map(function(){
return [
$('td,th',this).map(function(){
return $(this).text();
}).get()
];
}).get();
$(document).ready(function() {
var myData = JSON.stringify(tableData);
alert(myData)
});
Here is a fiddle showing the code in action:
http://jsfiddle.net/FWCXH/