Populating table with json data - javascript

I am trying to populate an HTML table using the JSON string retrieved from a $.getJSON() call. The $.getJSON() call is working fine. But I am not able to populate an html table with the retrieved json data. Please help me with my code..I'm new to this..
function loadTable(result){
if(result.groups="no"){
var num_rows = result.noofteams;
var rows = "";
for(var i=0;i<num_rows;i++){
rows +='<tr>'+result.noofteams+'</tr>';
}
$("#container").append(rows);
Here result is the json object that i am receiving. result.noofteams is giving proper value (i have checked it). But the problem is, i am unable to populate #container with result.noofteams Please help..

u used = while u need == or === for conditions
function loadTable(result){
if(result.groups==="no"){
var num_rows = result.noofteams;
var rows = "";
for(var i=0;i<num_rows;i++){
rows +='<tr><td>'+result.noofteams+'</td></tr>';
}
$("#container").append(rows);
}
}
EDIT: Add <td> they are important as well

It's much cleaner to work with JSON like so...
for (i in result) {
rows += '<tr>' + result[i]['noofteams'] + '</tr>';
}

Related

how can i make this ajax code work with any kind of html file

I have a ajax call which will get some data from database and I have to load these into a html file. But, the problem is I have different html files and I do not know the content of html file
I have tried it for around 2-3 days and have searched different ways to append data to a html file.
I have made some changes in the code. please assume that the code is working fine.
thank you.
$.ajax({
type: "GET",
url: "api/dataFromDataBase",
success: function (data) {
tableHead = data[0].split("?");//contains data from database
$("#databaseContent").append("<tr>");
for (var i = 0; i < 80; i++) {
$("#databaseContent").append("<th>" + tableHead[i] + "</th>");
}
$("#tableHeading").append("</tr>");
tableHead += data[0];
$("#FromHtml").append(data[1]);
},
});
in this file #databaseContent is an id in the html, so i can easily append the data. but I have no idea about what the html contains. Is their any way i can append data to it??
If you don't have a point of injection on a successful Ajax call. You can append this entire table at the end of the html page.
// all of this within the success call of the AJAX
var tableHead = data[0].split("?");//contains data from database
var tableEle = document.createElement("table");
var tableBody = document.createElement("tbody");
var tableTr = document.createElement("tr");
for (var i = 0; i < 80; i++) {
var cell = document.createElement("th");
var cellText = document.createTextNode(tableHead[i]);
cell.appendChild(cellText);
row.appendChild(cell);
}
tableBody.appendChild(tableTr);
tableEle.appendChild(tableBody);
document.body.appendChild(tableEle);
What we are trying to do here is, create a table element and within the loop creating the content of the table and at the end we're appending the newly created table to the
"document.body". This should work for all html since all html pages have a body tag.

How to get complete data from (html) bootstrap table when pagination is turned on

I am using bootstrap table in my web page and want to get complete textual data from all table cells, when pagination is on. I have tried the following method and it returns all the data:
var data = $('#' + tableID).bootstrapTable('getData')
Now when i traverse data object to get value for every cell it works fine but, for those cells which have some nested html , for example:
<td class="danger">cell 4</td>
<td>
google
</td>
Now, in this case, i want to get value for second cell as google but it returns me whole html as
google
Any idea, how i can get only textual value.
I can't do any server side operation, I have to achieve this using javascript/jquery. I have also tried using jquery:
function getColData(tableID,colIndex) {
var colArray = $('#' + tableID + ' td:nth-child'+'('+colIndex+')').map(function(){
return $(this).text();
}).get();
return colArray
}
it returns data correctly but only which is visible on active page and i want all the data.
Based on your file on JSFiddle I have modified the JS part as follows, this will get you the text on every td(i.e. text or text content) and not the values of their attributes. Basically this traverses through the DOM searching for tags embedded in ones - except for those on the table header - then obtains the text value.
var table = $('#table'), button = $('#button');
button.click(function() {
var data = [];
table.find('tr:not(:first)').each(function(i, row) {
var cols = [];
$(this).find('td').each(function(i, col) {
cols.push($(this).text());
});
data.push(cols);
});
alert(data);
});
You can see it in action here
UPDATE:
This will get you all data regardless of pagination, also it will strip tags and nested tags.
var table = $('#table'), button = $('#button');
button.click(function() {
var messedData = table.bootstrapTable('getData');
var data = [];
$.each(messedData, function(i, row) {
var rowData = {
'name': row['0'],
'star': row['1'],
'forks': row['2'],
'desc': row['3'],
}
for (prop in rowData) {
var tmp = document.createElement("div");
tmp.innerHTML = rowData[prop];
rowData[prop] = tmp.textContent || tmp.innerText || "";
}
data.push(rowData);
});
console.log(data);
});
You can see it here
Since the actual data is coming in as a string, I don't think bootstrap-table can't differentiate it from the other data. The simple solution I can think of is to use substring() to extract the data from the cells that contain custom html.
http://jsfiddle.net/vwg5Lefz/
The alternative is to go through the generated table <td> and use text() to get the text data from the cells.
http://jsfiddle.net/n0djy60v/

Get edit item value in RadGrid client-side

i'm looking for somone that can help me on this problem:
i've a Telerik RadGrid in edit-mode, after pressing radgrid's update button i do some checks into a javascript file; i want to check the value in some cells that are in edit mode but i don't know how to see the value.
I try to explain better with an example: i have some columns editable and some read-only, for the read-only columns i can view the value but for the editable columns i view all the html of the cell and i don't know how to get only the value, here is the code
function calculate(dgRDO) {
var grid = $find(dgRDO).get_masterTableView();
var righe = grid.get_editItems();
for (var i = 0; i < righe.length; i++) {
var row = righe[i];
//i can view this value, CODART column is ReadOnly
var codart = grid.getCellByColumnUniqueName(row, "CODART").innerHTML;
//i cannot view only the value but i view the entire html of the cell, PREZZO column is editable
var prezzo = grid.getCellByColumnUniqueName(row, "PREZZO").innerHTML;
}
Thanks for any suggestion
RESPONSE FROM TELERIK (IT WORKS)
In order to easily access RadGrid cells client-side you could use the ClientDataKeyNames property. It should contain the DataField names of the columns that will be accessed on the client. Illustration on extracting key values client-side is available in this article.
A sample function for accessing a column that is added to the ClientDataKeyNames collection would look similar to this:
function command(sender, eventArgs) {
var grid = $find("<%= RadGrid1.ClientID %>");
var masterTableView = grid.get_masterTableView();
var editItem = masterTableView.get_editItems()[0];
var cellValue = editItem.getDataKeyValue("Quantity");
}
Try this
var prezzo = grid.getCellByColumnUniqueName(row, "PREZZO").val();

innerHTML not updating display

First, hello everyone as I'm new here.
To summarize my problem, I read the content of an XML file to display in a table.
The basic function to do this works well, I created a derivated function to include a search filter related to an input field.
The search algorithm works well and I'm able to preview the HTML code of the search result using the alert() function and this code seems proper and can be displayed in a browser properly as it would be supposed to. However the innerHTML code of the concerned div is not updated...
I would appreciate any kind of input or solution anyone could provide as I've been stuck on this ! Thanks !
Here is the code :
function printListMod2(){
//Search parameters ?
var searchContent = document.getElementById("searchField").value;
var i=0;
newHTML = "<table id=\"tableInstrus\">";
for (i=0;i<listInstrus.length;i++){
filename = returnFilename(i);
title = returnTitle(i);
tempo = returnTempo(i);
sample = returnSample(i);
multi = returnMulti(i);
style1 = returnStyle1(i);
style2 = returnStyle2(i);
var regEx = new RegExp(searchContent, 'gi');
var resultSearch = title.match(regEx);
if(resultSearch!=null){
if(i%2==0){
newHTML += "<tr class=\"tr0\"><td class=\"idColumn\">"+(i+1)+"</td><td class=\"emptyColumn\"></td><td class=\"nameColumn\">"+title+"</td><td class=\"tempoColumn\">"+tempo+"</td><td class=\"sampleColumn\">"+sample+"</td><td class=\"multiColumn\">"+multi+"</td><td class=\"styleColumn\">"+style1+"</td><td class=\"styleColumn\">"+style2+"</td><td class=\"addLink\"><a id="+filename+" onclick=\"addLinkToPlaylist("+i+")\"><img title=\"Add to playlist\" class=\"addButton\" src=\"images/buttonAdd.png\"/></a></td><td class=\"playLink\"><a onclick=\"playTrack("+i+","+true+")\"><img title=\"Play this track\" class=\"playButton\" src=\"images/buttonPlaySmall.png\"/></a></td></tr>";
}
else{
newHTML += "<tr class=\"tr1\"><td class=\"idColumn\">"+(i+1)+"</td><td class=\"emptyColumn\"></td><td class=\"nameColumn\">"+title+"</td><td class=\"tempoColumn\">"+tempo+"</td><td class=\"sampleColumn\">"+sample+"</td><td class=\"multiColumn\">"+multi+"</td><td class=\"styleColumn\">"+style1+"</td><td class=\"styleColumn\">"+style2+"</td><td class=\"addLink\"><a id="+filename+" onclick=\"addLinkToPlaylist("+i+")\"><img title=\"Add to playlist\" class=\"addButton\" src=\"images/buttonAdd.png\"/></a></td><td class=\"playLink\"><a onclick=\"playTrack("+i+","+true+")\"><img title=\"Play this track\" class=\"playButton\" src=\"images/buttonPlaySmall.png\"/></a></td></tr>";
}
}
}
newHTML += "<tr><td class=\"idColumn\"></td><td id=\"emptyColumn\"></td><td class=\"nameColumn\"></td><td class=\"tempoColumn\"></td><td class=\"sampleColumn\"></td><td class=\"multiColumn\"></td><td></td><td></td></tr>";
newHTML += "</table>";
alert(newHTML); //this displays the HTML code properly
document.getElementById("listDiv").innerHTML = newHTML; //this doesn't seem to do anything...
}
Is your script being executed before the document has finished loading?
Then it won't find #listDiv because the div doesn't exist yet.
I would check the javascript console output for errors and check if the following code doesn't return undefined:
{
...
console.log( document.getElementById('listDiv') );
}

Paging in java script

I am working in chrome extension, I want to make paging for table which is fill dynamically using sqlite queries.
I am using this tutorial to make the paging and make some modification in init function
http://en.newinstance.it/2006/09/27/client-side-html-table-pagination-with-javascript/
When I want to get the length of the table after filling it, the dom seems to be not ready and the result return as ZERO of table length, here's some of my code..
function ViewAllNotes(db){
var allListItems;
var cur = fromDateToString(new Date(),"date");
db.transaction(function(tx) {
tx.executeSql("SELECT NOTE_DESC,NOTE_DATE,NOTE_TIME FROM NOTES where NOTE_DATE = ? order by NOTE_TIME desc ",[cur],function(tx,result){
alert(result.rows.length);
for(i=0;i< result.rows.length;i++){
tr= "<tr>";
tr=tr+ "<td>"+ result.rows.item(i)['NOTE_DESC']+"</td>";
tr=tr+ "<td>"+ result.rows.item(i)['NOTE_TIME']+"</td>";
tr=tr+ "</tr>";
allListItems+=tr;
}
var tableContent= " <thead><tr><th id='activityHeader'>Activity</th> <th>Time</th></tr></thead>";
tableContent = tableContent+"<tbody>"+allListItems+"</tbody>";
$("table#notes").append(tableContent);
//$('#notes').dataTable();
},onError);
});
}
EDIT
At the begining of the js file I make like this
ViewAllNotes(db);
var rows = document.getElementById("notes").rows;
alert("rows "+rows.length);
then call the pager class, but also it alerts with zero ?
SQL calls are aysynchronous. Your code that tests for length will not have a length available until the SQL finishes and fires the callback.

Categories