add 2 value to a div and then spliting? - html

Not sure if this is the best way but, as can see below I am getting the current page and adding it to the div of "load_more" I then use this value in a function to + 1. however I now need another value added to this "total pages" and I am not sure where to add it do (another div). Can I add it to the div (the same one on click) also then slit out the results? in the load more click function?
Thanks
gets the value
$('.load_more').live("click", function(){ //When user clicks
var currentPage = parseInt($(this).attr('id'), 10);
++currentPage;
alert(currentPage);
dosomething(currentPage);
});
set the value
var currentPage = "";
var totalPages = ";"
$.each(r.MESSAGES, function(key, value){
currentPage += value.CURRENTPAGE;
totalPages += value.TOTALPAGES;
})
jQuery('.load_more').attr("id", currentPage);
html
<div id="load-more">
<a class="load_more" id="123" href="#">
Load More
</a>
</div>

Instead of adding DOM attributes to your class load_more it can be an idea using jQuery data storage. http://api.jquery.com/data/
Very simple to use: http://jsfiddle.net/j3bb5/
$('.load_more').data("current_page", 1); // Setting variable current_page;
alert( $('.load_more').data("current_page") ); // Getting variable current_page, alerts "1"
And you can store Objects as well: http://jsfiddle.net/j3bb5/1/
$('.load_more').data("current_page", { // Setting variable current_page;
id: 1,
name: "My page 1"
}); // Setting variable current_page;
alert( $('.load_more').data("current_page").id ); // Getting variable current_page, alerts "1"
alert( $('.load_more').data("current_page").name ); // Getting variable current_page, alerts "My page 1"
And now to your example: http://jsfiddle.net/j3bb5/4/
Don't know what variable r is but something like this?
var r = {
MESSAGES: [{
CURRENTPAGE: 1,
TOTALPAGES: 4
},{
CURRENTPAGE: 2,
TOTALPAGES: 4
}]
};
Function doSomething does nothing ;)
function doSomething(CURRENTPAGE, TOTALPAGES) {};
Setting the values from r.MESSAGES using jQuery.fn.data method
First we define our temporary CURRENTPAGE and TOTALPAGES variables
var CURRENTPAGE = 0, TOTALPAGES = 0;
Loops throw r.MESSAGES and updating CURRENTPAGE and TOTALPAGES
$.each(r.MESSAGES, function(key, value) {
CURRENTPAGE += value.CURRENTPAGE;
TOTALPAGES += value.TOTALPAGES;
});
Binds them to the selector .load_more
$('.load_more').data("CURRENTPAGE", CURRENTPAGE);
$('.load_more').data("TOTALPAGES", TOTALPAGES);
Click Event on .load_more
$('.load_more').live("click", function() {
Getting CURRENTPAGE and TOTALPAGES from data method:
var CURRENTPAGE = $(this).data("CURRENTPAGE");
var TOTALPAGES = $(this).data("TOTALPAGES");
Alerting the values:
alert("CURRENTPAGE: " + CURRENTPAGE);
alert("TOTALPAGES: " + TOTALPAGES);
And now increases the values by one: Note the double + sign before our variables. It means you add one to the value. Se a little deeper explanation: http://jsfiddle.net/j3bb5/6/
$(this).data("CURRENTPAGE", ++CURRENTPAGE);
$(this).data("TOTALPAGES", ++TOTALPAGES);
doSomething(CURRENTPAGE, TOTALPAGES);
});

Related

Titanium appcelerator : Lazy loading concept in table view while loading data using JSON

I have used Google Places API in order to display various places. I want at a time to display 20 places and when user scrolls the table view and reaches last field I want to add the rest of data and so on. I have created a function which returns the view and works perfectly excluding one thing. When further data is not available then it goes on loading the last data which is already loaded. Here goes my code.
Ti.include('Functions/get_lat_long.js');
var myTable = Ti.UI.createTableView();
var next_page;
var nxt_pge_tkn;
var tableData = [];
function json_parsing(url,firsttime,winloading)
{
var view1=Ti.UI.createView({
//height : '100%',
width : '100%',
backgroundColor : '#EDDA74',
top : '10%',
borderColor : "black"
});
//For storing url in case next_page_token variable is invalid
var curloc=Ti.App.Properties.getString("curlocation");
//calling method in order to retrive latitude and longitude of current location
get_latitude_longitude(curloc);
//setting the base url that have been initialized in global.js file
var baseurl=Ti.App.Properties.getString("preurl");
//storing lat and lng file that have been initialized in get_lat_lon.js file get_latitude_longitude function
var lat=Ti.App.Properties.getString("curlat");
var lng=Ti.App.Properties.getString("curlng");
//Storing radius which have been initialized in global.js file
var radiusmts=Ti.App.Properties.getInt("curradius")*1000;
//setting location type from the value that have been selected in app.js file by user
var loc_type=Ti.App.Properties.getString("curcategory");
//fetching and storing key which have been initialized in global.js file
var key=Ti.App.Properties.getString("apikey");
if(firsttime==true)
{
winloading.open();
var completeurl=baseurl+lat+","+lng+"&radius=" + radiusmts+ "&types=" + loc_type+ "&sensor=false&key=" + key;
}
else
{
winloading.show();
var completeurl=url;
}
var client = Ti.Network.createHTTPClient();
Ti.API.info("complete url " +completeurl);
client.open('GET',completeurl);
client.onload = function(e) {
//For getting next_page_token so that next page results could be displayed
var json = JSON.parse(this.responseText);
if(json.next_page_token)
{
Ti.API.info("Next page token found ");
next_page=true;
nxt_pge_tkn=json.next_page_token;
}
else
{
Ti.API.info("Next page token not found ");
next_page=false;
}
if(json.results.length==0)
{
var lblno_record=Titanium.UI.createLabel({
text : "No Record Found",
color : "black",
font : {fontSize : "25%" }
});
view1.add(lblno_record);
}
else
{
for(var i=0; i <json.results.length;i++)
{
//Ti.API.info("Place " + json.results[i].name+ " Lat " + json.results[i].geometry.location.lat + " Lng " + json.results[i].geometry.location.lng);
var row = Ti.UI.createTableViewRow({
className : "row"
//height : "80%"
});
//For temporary storing name in name variable
var name=json.results[i].name;
//Logic for shortening string in order to avoid overlapping of string
(name.length>35)?name=name.substr(0,34)+ "..." :name=name;
//Create label for displaying the name of place
var lblname=Ti.UI.createLabel({
//text : json.results[i].name,
text : name,
color : "black",
font : {fontSize : "20%"},
left : "22%",
top : "5%"
});
Ti.API.info("Name :- " + name);
row.add(lblname);
var add= json.results[i].vicinity;
(add.length>125) ? add=add.substr(0,123)+ ". ." : add=add;
var lbladdress=Ti.UI.createLabel({
text : add,
color : "black",
font : {fontSize : "15%"},
left : "22%",
top : "30%",
width : "71%"
});
row.add(lbladdress);
var imgico=Ti.UI.createImageView({
image : json.results[i].icon,
height : "90",
width : "90",
left : "1%",
top : "3%"
//bottom : "10%"
});
row.add(imgico);
tableData.push(row);
}
//setting data that have been set to mytable view
myTable.setData(tableData);
view1.add(myTable);
}
winloading.hide();
};
client.onerror=function(e){
alert("Network Not Avaliable");
};
myTable.addEventListener('scroll',function(e){
var first=e.firstVisibleItem;
var visible=e.visibleItemCount;
var total=e.totalItemCount;
Ti.API.info("Value of next_page_token before loop " + next_page);
if(next_page==true && first+visible==total )
{
Ti.API.info("Value of next_page_token in loop " + next_page);
var newurl="https://maps.googleapis.com/maps/api/place/nearbysearch/json?pagetoken="+nxt_pge_tkn+"&sensor=false&key="+key;
firsttime=false;
winloading.show();
//myTable.removeEventListener('scroll',function(e){});
json_parsing(newurl,firsttime,winloading);
//get_next_page(newurl);
}
});
client.send();
return view1;
client.clearCookies();
}
I was looking through your code and I would like to point:
There is an important issue with the block:
myTable.addEventListener('scroll',function(e){
...
});
this block is called each time you call your json_parsing function. Because of that you will have several functions attached to myTable scroll event. I'm sure that this isn't your intention. You should put it out of json_parsing.
About your specific issue you could try to look at the json.next_page_token value in your client.onload function:
client.onload = function(e) {
//For getting next_page_token so that next page results could be displayed
var json = JSON.parse(this.responseText);
Ti.API.info(JSON.stringify(this.responseText);
if(json.next_page_token)
{
...
maybe the value is an empty object {} or a 'false' string that will return a thruthy value. Don't forget that in javascript there are only 6 falsy values: false, undefined, null, 0, '' and NaN.
In practice this is a minor issue, but in documentation HTTPClient.onload and HTTPClient.onerror functions must be set before calling HTTPClient.open function
BTW, you have unreachable code at the end of your json_parsing function, but I think you already know that :-)
client.send();
return view1;
client.clearCookies(); //Unreachable code

Kendo UI Grid Get Row Values

I am trying to get the row item values (name, email, age) but I'm only able to get the first item by using the code below.
How can I get other row text by changing tr:eq(1) code or is there any other way to get two items value?
$("#grid_").kendoDropTarget({
drop: function (e) {
var data = grid.dataItem("tr:eq(1)");
// I only get first row but I need to dynamically get any row items.
alert(data.name);
}
});
plz try this..
var entityGrid = $("#DataGrid").data("kendoGrid");
var data = entityGrid.dataSource.data();
var totalNumber = data.length;
for(var i = 0; i<totalNumber; i++) {
var currentDataItem = data[i];
VersionIdArray[i] = currentDataItem.VersionId;
}
Thanks Sanjay however I was looking to just select a row items and this is what I got:
//Selecting Grid
var gview = $("#grid").data("kendoGrid");
//Getting selected item
var selectedItem = gview.dataItem(gview.select());
//accessing selected rows data
alert(selectedItem.email);
So it worked out perfect.
if your grid is set to selectable: true, use the following:
var mygrid = $("#grid").kendoGrid({
selectable: true
});
mygrid.on("click", "tr", function() {
var datarowindex = mygrid.data("kendoGrid").items().index(mygrid.data("kendoGrid").select());
var datarowid = mygrid.data("kendoGrid").dataItem(mygrid.data("kendoGrid").select()).MyId;
alert("index: " + datarowindex + " | value: " + datarowid);
});
if your Kendo UI Grid is set to selectable: false, use the following:
var mygrid = $("#grid").kendoGrid({
selectable: false
});
mygrid.on("click", "tr", function() {
var datarowindex = mygrid.data("kendoGrid").items().index($(this));
var datarowid = mygrid.data("kendoGrid").dataItem($(this).closest("tr")).MyId;
alert("index: " + datarowindex + " | value: " + datarowid);
});
where MyId is the property you are looking for.
I usually use the model from the event. Sometimes, actually very rarely, the row gets deselected and so, the .select() will return a 0 length object which will throw error while trying to access undefined properties.
You might be safer using: e.model.name

How do I return the number of rows of a table according to a search criteria in Web SQL?

I have created a database called todo with table name todo having fields like title,date etc. The table is empty right now.
I have defined a function which takes title as parameter and check whether table contains that title or not.
It should return the number of rows.
GetTitle function:
todo.webdb.GetTitle = function(title) {
var db = todo.webdb.db;
db.transaction(function(tx){
tx.executeSql("SELECT title FROM todo WHERE title=?", [title],
loadTitle,
todo.webdb.onError);
});
}
loadTitle Function:
function loadTitle(tx, rs) {
return rs.rows.length;
}
GetTitle Function is called:
row=todo.webdb.GetTitle("Hello");
alert(row);
I get alert 'undefined' it should return 0
I am confused right now how to resolve this issue.
I think the transactions are asynchronous, so you need to callback function to receive the value.
todo.webdb.GetTitle = function(title, callback) {
var db = todo.webdb.db;
db.transaction(function(tx){
tx.executeSql("SELECT title FROM todo WHERE title=?", [title],
(function loadTitle(tx, rs){
callback( rs.rows.length );
}),
todo.webdb.onError);
});
}
todo.webdb.GetTitle( "Hello", function(count){
alert( "count = " + count );
});
Here's an excellent tutorial for more information.
http://blog.darkcrimson.com/2010/05/local-databases/
Update
Don't make functions inside a loop for this main reason.
Both i and title are referencing a value created out of local scope.
So the last value of assigned to both i and title will be displayed.
for (i = 0; i < itemcount; i++) {
alert('i outside if:' + i);
var title = x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
todo.webdb.GetTitle( title, function (count) {
if (!count) {
alert('i inside if:' + i);
alert( title );
}
});
}
Fix:
Generate a function that has the values locked in a closure.
var createTitleCallBack = function( i, title ){
return function (count) {
if (!count) {
alert('i inside if:' + i);
alert( title );
}
};
};
for (i = 0; i < itemcount; i++) {
alert('i outside if:' + i);
var title = x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
todo.webdb.GetTitle( title, createTitleCallBack( i, title ) );
}

audio tag cannot be parsed in html5 page

I link this JS page to an XML all element is views but the audio tag in xml file is not views in the html5 page ..any suggestion how to make this function retrieve the audio file and show it as html5 audi player.
init: function () {
//jQuery ajax call to retrieve the XML file
$.ajax({
type: "GET",
url: XMLLIST.xml,
dataType: "xml",
success: XMLLIST.parseXML
});
}, // end: init()
parseXML: function (xml) {
//Grab every single ITEM tags in the XML file
var data = $('item', xml).get();
//Allow user to toggle display randomly or vice versa
var list = (XMLLIST.random) ? XMLLIST.randomize(data) : data;
var i = 1;
//Loop through all the ITEMs
$(list).each(function () {
//Parse data and embed it with HTML
XMLLIST.insertHTML($(this));
//If it reached user predefined total of display item, stop the loop, job done.
if (i == XMLLIST.display) return false;
i++;
});
}, // end: parseXML()
insertHTML: function (item) {
//retrieve each of the data field from ITEM
var url = item.find('url').text();
var image = item.find('image').text();
var audio=item.find('audio').text();
var title = item.find('title').text();
var desc = item.find('desc').text();
var html;
//Embed them into HTML code
html = '<div class="item">';
html += '<a href="' + url + '"><image"' + image + '" alt="' + title + '" />';
html += '<span>' + title + '</span></a>';
html += '<audio control="control"><span> ' +audio+' </span></audio>';
html += '<p>' + desc + '</p>';
html += '</div>';
//Append it to user predefined element
$(html).appendTo(XMLLIST.appendTo);
}, // end: insertHTML()
randomize: function(arr) {
//randomize the data
//Credit to JSFromHell http://jsfromhell.com/array/shuffle
for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
return arr;
} // end: randomize()
}
AFAIK .each() is used to iterate over a jQuery object, if you want to iterate over an array use $.each()
Here you have
$(list).each(function () {
which should be
$.each(list, function () {
since list is an array of dom nodes and not a jQuery object

Problem in getting right result for select box

I am using jQuery as:
$(document).ready(function(){
test("price");
alert("hi");
$("#item2").change(function()
{
sort= $("#item2").val();
test(sort);
});
});
Function test() is some JavaScript function, my problem is when page loads function calls by "price" parameter. Now when I select some item from select box function test() is called using sort parameter (verify by alert box). but I am not getting the correct result. I mean when I select option from select box than also my result of test() is as with "price" , I suppose it might be the problem because of jQuery's $(document).ready(function(){,. test() function make some html code based on the parameter and show it on the web page.
Please suggest me what can be the solution
EDIT:
function test() is :
function test(sort)
{
<%
Ampliflex ms = Ampliflex.getInstance();
String solrIP = ms.getSolrIP();
String solrPort = ms.getSolrPort();
String rows = ms.getSearchResultCount();
%>
solrIP='<%= solrIP %>'; // get Solr IP address
solrPort='<%= solrPort %>'; // get Solr Port number
rows='<%= rows %>'; // get number of results to return
solrURL="http://"+solrIP+":"+solrPort;
var query="${searchStr}"; // get the query string entered by ECommerce user
query=query.replace(/[^a-zA-Z 0-9*?:.+-^""_]+/g,''); // Remove special characters
query=query.replace(/\*+/g,'*'); // Replace multiple occurrence of "*" with single "*"
var newquery=query;
if(parseInt(query)==NaN)
{
var lowerCaseQuery=query.toLowerCase();
newquery=lowerCaseQuery;
}
else{
var lowerCaseQuery=query;
}
// sort= document.getElementById("item2").value;
$.getJSON(solrURL+"/solr/db/select/?qt=dismax&wt=json&&start=0&rows="+rows+"&q="+lowerCaseQuery+"&hl=true&hl.fl=text&hl.usePhraseHighlighter=true&sort="+sort+" desc&json.wrf=?", function(result){
var highlight = new Array(result.response.numFound);
$.each(result.highlighting, function(i, hitem){
var rg = /<em>(.*?)<\/em>/g;
var res = new Array();
var match = rg.exec(hitem.text[0]);
while(match != null){
res.push(match[1])
match = rg.exec(hitem.text[0]);
}
highlight[i]=res[0]
for (j=1 ;j<res.length;j++)
{
highlight[i]= highlight[i]+","+res[j];
}
});
var html="<table><tr>"
var count=0;
var alt="NoImage";
var size="3pt";
var id;
var flag=1; // Flag for error messages
border="1";
// If no search results
if(result.response.numFound==0)
{
var msg= "<hr /><font size="+size+" >We're sorry, we found no results for <b>"+document.getElementById("queryString").value+"</font><hr />";
}
else
{
/* var msg= "<hr /><font size="+size+" >Total Results Found <b> "+ result.response.numFound+"</b> for "+"<b>"+document.getElementById("queryString").value+"</b> keyword</font><hr /> ";*/
if (newquery==lowerCaseQuery)
{
var msg= "<hr /><font size="+size+" >Total Results Found <b> "+ result.response.numFound+"</b> for "+"<b>"+query+"</b> </font><hr /> ";
}
else
{
var msg= "<hr /><font size="+size+" >There were no exact matches for <b> "+ query+"</b> , so we searched automatically for "+"<b>"+query+"</b> and yielded "+result.response.numFound+" result(s)</font><hr /> ";
}
// Parse solr response and display it on web page
$.each(result.response.docs, function(i,item){
var word = new Array();
word=highlight[item["UID_PK"]].split(",");
var result="";
var j=0;
for (j=0 ;j<=item.text.length;j++)
{
result = result+item.text[j]+"<br>";
}
for (j=0 ;j<word.length;j++)
{
result=result.replace(word[j],'<em>' + word[j] + '</em>');
}
html+="<td><table>";
var src=item.image;
id="id";
if(src!= null && src!= ""){
html+="<p><tr><td><br>"+"<img id= "+id+ " src="+src+ " border="+border+ " /></td></tr>";
count=count+1;
html += "<tr><td><b>ImagePath</b> "+ item.image+"</td></tr>";
}
// If not insert a default image
else
{
src="images/products/default.jpg";
html+="<tr><td><br><p>"+"<img id= "+id+ " src="+src+ " border="+border+" /></td></tr>";
count=count+1;
html += "<tr><td><b>ImagePath</b> "+"No image path found" +"</td></tr>";
}
html += "<tr><td>UID_PK: "+ item.UID_PK+"</td></tr>";
html += "<tr><td>Name: "+ item.name+"</td></tr>";
html+="<tr><td><b>Price: $"+item.price+"</td></tr>";
html+="<tr><td> "+result+"<br></td></tr>";
html+="</p></table></td>"
if(count%3==0)
{
html+="</tr>"
html+="<tr>"
}
});
html+="</table>"
}
$("#text_container").html(msg);
$("#result").append(html);
}
});
});
}
Your question isn't particularly clear, but your alert code only fires when the document is ready - it is not inside the "change" event function.
Try using the following to see what value is being returned when you change the select box:
$(document).ready(function(){
test("price");
$("#item2").change(function()
{
sort= $("#item2").val();
alert(sort);
test(sort);
});
});
When changing the select box, you should get an alert with the value you have chosen, which will help you understand why the test() function isn't functioning as you expect.
If you amend your question to include the HTML of the select box and the test() function itself I will amend my answer to help.
The JQuery code that you have posted is working fine. Demo: http://jsfiddle.net/DtnUr/
We need more details to figure out the issue, such as your HTML code and JS functions.