Paging in java script - javascript

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.

Related

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/

how to display only 4 result in each page using html & sqlite

This is me once again as I got some error in previous question in the code. So asking this question once again.
This is code from phonegap app from index html page. I don't know how to get only 4 result from database at each page when a sqlite query processed?
Also I want to add next page button. When clicking on this button next 4 result from database should come. This is code.
function querySuccess(tx, results){
var len = results.rows.length;
var output = '';
for (var i=0; i<len; i++){
output = output + '<li id="' + results.rows.item(i).id + '">' + results.rows.item(i).list_action + '</li>';
}
messageElement.html('<p>There are ' + len + ' items in your list:</p>');
listElement.html('<ul>' + output + '</ul>');
}
Dividng your solution into 3 phases
Phase 1: Using LIMIT Clause you can limit number of rows to be displayed
SELECT expressions FROM tables WHERE conditions ORDER BY expression [ ASC | DESC ] LIMIT number_rows OFFSET offset_value;
For Example:
SELECT employee_id, last_name, first_name
FROM employees
WHERE favorite_website = 'divyashah.in'
ORDER BY employee_id DESC
LIMIT 4;
Phase 2:
As the code provided by you is not efficient to explain but still... Now for your Next button
1) Fetch number of rows from your database table (mysql_num_rows).
2) Store that number in a Variable say 'a'.
3) Divide it(a) with 4 and store it in variable 'b'.
4) Use if > if(b!=0) {display next button} else {no need to display}
Phase 3:
This will fetch your first four rows i.e. from 0 to 4.
<?PHP
$fetch = mysql_query("SELECT * FROM table LIMIT 0, 4")or
die(mysql_error());
?>
Now how can you make the next page show the next 4 records?
you simply have to store the value of the starting row in a variable and pass it in the URL as a GET variable. Also have to check if there was a value already passed or not so we can set a default value in case it wasn't (zero to start from first row):
<?PHP
//check if the starting row variable was passed in URL or not
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
//we give the value of the starting row to 0 because nothing was found in URL
$startrow = 0;
//otherwise we take the value from the URL
} else {
$startrow = (int)$_GET['startrow'];
}
?>
Now your query should have this new variable ($startrow) in the LIMIT clause
<?PHP
//this part goes after the checking of the $_GET var
$fetch = mysql_query("SELECT * FROM table LIMIT $startrow, 4")or
die(mysql_error());
?>
Now to see the next 4 records you should have a link which will add 4 to $startrow so you can view the next 4 records
<?PHP
//now this is the link..
echo 'Next';
?>

Getting and updating the right table html values with jquery

I have tried to get the solution on line but can't find one.
I will try and explain my problem because i can't make this in fiddle because the values are from the database.
I have two tables one displays data from the database.I have a button which when I click add it copy the contents of the first table and append them to the second table.
I am able to do it.
Now the issue am stuck is that i want to be able to check if i have added a data before in the second table and update the one that was added.
My jquery code here :
$('#centerElem tr').each(function(index, items){
$(this)find('input:checked')each(function(){
$this= $(this);
var chkItemcol = $this.parent().siblings('td');
var chklen = chkItemcol,length;
var chkItemValue = chkItemcol.eq(0).text(); var chkItemPrice = chkItemcol.eq(chklen-1).text();
var sumprice=0;
createrow ="<tr class='data'><td class='itemQty'>"+count+"</td>";
// iterate through the columns.
var mlen = chklen-1;
for(var i = 0; i<chklen; i++){ // add class to the item name
if(i == 0){
createrow += "<td class='name'>";
}else{
createrow += "<td>";
}
createrow += $this.parent().siblings('td').eq(i).text();
}
createrow += "</td>";
//alert(createrow);
createrow += "<td class='subtotal'></td></tr>";
if(i == (mlen)){
sumprice = ($this.parent().siblings('td').eq(0).text()) * ($this.parent().siblings('td').eq().text(mlen));
}
createTotal = "<tr><td>Total</td><td class='totalsum'>"+sumprice+"</td></tr>";
$('.ordertable .name').each(function (index, item) {
// get the checked <td>
var chkItemcol = $this.parent().siblings('td');
// get the checked row numbers of columns
var $item = $(item);
$data = $item.text();
var olen = $($item.siblings()).length;
var itemprice;
var subTotal
if ($data == chkItemValue) {
count++;
flag = true;
//get the item price
itemprice = $($item.siblings()[olen - 2]).text();
//multiple the qty with the item price
subTotal = count * itemprice;
// set the qty
$($item.siblings()[0]).text(count);
// set the subtotal.
$($item.siblings()[olen - 1]).text(subTotal);
return count;
} else {
count = 1;
itemprice = $($item.siblings()[olen - 2]).text();
alert("first add price " + itemprice);
subTotal = count * itemprice;
$($item.siblings()[olen - 1]).text(subTotal);
flag = false;
return count;
}
});
// check if the item was added to the ordered list table
if (flag) {
count++;
} else {
count = 1;
$(createrow).appendTo($('.ordertable > tbody'));
}
});
});
here is my html part, the table that display the database values.
<table><thead><tr><td><input type="checkbox" name="checkall"></td><td>Dish Name</td><td>Discription</td><td>ingredients</td><td>type</td><td>price</td></tr></thead>
<tbody>
<tr><td><input type="checkbox" name="chk" id="chk"/></td><td class='name'>Rice </td><td>white parboiled rice</td><td>rice</td><td>none</td><td>300</td></tr>
<tr><td><input type="checkbox" name="chk" id="chk"/></td><td class='name'>Beans </td><td>parboiled beans</td><td>beans an d salt/td><td>none</td><td>400</td></tr>
</tbody>
</table>
Here is the one i am appending the copied values to :
<TABLE class="ordertable" style="width:100%; border-collapse:collapse; border: solid 1px #000000">
<TBODY>
</TBODY><TFOOT></TFOOT></TABLE>
How can i do this ?
May I suggest a different approach? Put your data model in pure Javascript variables and use those for calculations etc. Only when done render the HTML. E.g.:
var products = {
rice: {name: 'Rice', description: 'White parboiled rice', price: 300},
beans: {name: 'Beans', description: 'Parboiled beans', price: 400}
};
var cart = {
rice: {quantity: 0, subtotal: 0},
beans: {quantity: 0, subtotal: 0}
};
This makes your life so much easier! Have a look at this jsFiddle
im not sure if this will solve much of what you're encountering. but there are some glaring typos in your html and jquery code. I have created a jsFiddle to make this easier for you to update.
watch for places where you're using , instead of . or forgetting . entirely in your js. Also make sure you're vigilant about closing your lines with ;. With your HTML you're doing well just looks like a typo in one of the closing </td>
I have added a list at the top of the JS section of the undeclared JS variables from your code that i guessed at.
heres the link: http://jsfiddle.net/6ryBL/3/
for templating of js you might want to have a look at creating javascript html templates using a templating language like EJS (http://embeddedjs.com/). Rather than 'building' the html piece by piece.
also added a 'check all' script thanks to https://stackoverflow.com/a/18537624/648350
EDIT: changed the JS to do what OP was asking for (would highly recommend a templating system and a localstorage/cookie solution to manage the cart data). Regardless, all cart data should be checked at server level before payment steps to confirm both stock and prices are correct.
http://jsfiddle.net/6ryBL/6/

Populating table with json data

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>';
}

Find Duplicate Records in HTML Table

I am using DataTable pulgin and had question about adding duplicate row.
When user add a record to (HTML) table I want to check if that record already exists in Table (on client side).
For example:
Column A
Row 1 ABC
Now if user try to add "ABC", I want to throw error.
Can anyone provide pointer how to achieve this using jQuery or Datatables?
function findInTable(str, tableID){
$('#' + tableID + ' tr').each(function(){
$(this).children('td').each(function(){
if ( $(this).html() == str ){
alert('found');
return false;
}
});
});
}
findInTable('ABC', 'mytable'); // <table id="mytable">...</table>
This should solve your problem. Tweak this
<script type="text/javascript">
<!--
function cellContent() {
var content=document.getElementsByTagName('td');
for(c=0;c<content.length;c++) {
alert ('td cell number '+(c+1)+' contains...\n ' +content[c].innerHTML);
}
}
onload=cellContent;
//-->
</script>
There is a hacky way to do this for smaller tables. Convert the rows into strings, and put them in an associative array, works best for single column tables, and there are ways to work with multiple columns
Hence lets say you insert ABC
if (tableData["ABC"] != undefined) tableData["ABC"] = 1;
else alert("Duplicate");
Also if loop should take care of adding the row to the UI

Categories