Retrieve data from selected row in an alert - javascript

I am building a Titanium iOS app. I am receiving JSON data from a server and populating a table. I have an image in each row that I swap out when the image is selected, then I show an alert to confirm their selection. My problem is displaying the SELECTED rows data in the alert. Here is my code:
//Create the row
var xhr = Ti.Network.createHTTPClient({
onload : function() {
Ti.API.debug(this.responseText);
var json = JSON.parse(this.responseText);
for ( i = 0; i < json.matches.length; i++) {
match = json.matches[i];
row = Ti.UI.createTableViewRow({
backgroundImage : 'images/matchesrowbackground.png',
selectionStyle : Titanium.UI.iPhone.TableViewCellSelectionStyle.NONE,
width : '90%',
height : '180px'
});
var acceptmatchView = Ti.UI.createView({
left : '0px',
top : '0px',
width : '60px',
height : '60px'
});
var acceptmatch = Ti.UI.createImageView({
image : 'images/nomatch.png',
left : '0px',
top : '0px',
width : '60px',
height : '60px'
});
//Add some more stuff to the row and add the rows to the table then do my tableview.EventListener
tableview.addEventListener('click', function(e) {
var imageView = e.row.children[0].children[0];
if (imageView.image == 'images/nomatch.png') {
imageView.image = 'images/match.png';
var alertWindow = Titanium.UI.createAlertDialog({
title : 'Accept This Match?',
message : 'Are you sure you want to accept this match? ' + '\n' + match.matchtype + '\n' + 'Time: ' + match.datetime + '\n' + 'At: ' + match.cname,
cancel : 1,
buttonNames : ['Yes', 'Cancel']
});
How do I get the selected rows data to show in the alert?

For that, you need to change the code like following
//Create the row
var xhr = Ti.Network.createHTTPClient({
onload : function() {
Ti.API.debug(this.responseText);
var json = JSON.parse(this.responseText);
for ( i = 0; i < json.matches.length; i++) {
match = json.matches[i];
row = Ti.UI.createTableViewRow({
backgroundImage : 'images/matchesrowbackground.png',
selectionStyle : Titanium.UI.iPhone.TableViewCellSelectionStyle.NONE,
width : '90%',
height : '180px',
rowId : i //custom property
});
//Add some more stuff to the row and add the rows to the table
tableview.addEventListener('click', function(e) {
var imageView = e.row.children[0].children[0];
if (imageView.image == 'images/nomatch.png')
{
imageView.image = 'images/match.png';
var matchSelected = json.matches[e.rowData.rowId];
var alertWindow = Titanium.UI.createAlertDialog({
title : 'Accept This Match?',
message : 'Are you sure you want to accept this match? ' + '\n' + matchSelected.matchtype + '\n' + 'Time: ' + matchSelected.datetime + '\n' + 'At: ' + matchSelected.cname,
cancel : 1,
buttonNames : ['Yes', 'Cancel']
});
}
});
I'm using a custom property rowId for identifying the selected row.

Related

Remove data undefined in popup map Javascript

I have json data, and the data is displayed in a pop up on a map
when there is a data that does not exist (Visibility), then the word undefined appears on the pop up
How to remove undefined text, so that it gets deleted on the pop up?
json data :
[{
"date":"03-03-2022",
"lat":-5.67,
"lng":80.65,
"weather":"2",
"temperature": "24.4",
"Humidity": "90",
"Wind": "100"}]
script js :
<script>
for (i = 0; i < dataJSON.length; i++) {
var weather = parseInt(dataJSON[i].weather)
var Coordinate = new L.latLng(([dataJSON[i].lat, dataJSON[i].lng]))
var marker = L.marker(Coordinate, { icon: customIcon })
marker.bindPopup('Date : ' + dataJSON[i].date + 'Temperature : ' + dataJSON[i].temperature + 'RH :' + dataJSON[i].Humidity
+ 'wind :' + dataJSON[i].Wind + 'Visibility :' + dataJSON[i].Vis
)
}
Pop Up :
Help me, Please . . .
You are getting the 'undefined' in Visibility since the property 'Vis' is not a part of json data.
You can use the following code in script.js to remove undefined from the popup and replace it with blank:
<script>
for (i = 0; i < dataJSON.length; i++) {
var weather = parseInt(dataJSON[i].weather)
var Coordinate = new L.latLng(([dataJSON[i].lat, dataJSON[i].lng]))
var marker = L.marker(Coordinate, { icon: customIcon })
marker.bindPopup('Date : ' + dataJSON[i].date + 'Temperature : ' + dataJSON[i].temperature + 'RH :' + dataJSON[i].Humidity
+ 'wind :' + dataJSON[i].Wind + (dataJSON[i].Vis == undefined?'':'Visibility :' + dataJSON[i].Vis)
)
}
</script>

Logical ">" and "<" not working inside Jquery function

I have the following code :
<script type="text/javascript">
jQuery(function($) {
var main_content = $('#container'),
position_top = $('#j_idt7\\:idA').position().top,
position_left = $('#j_idt7\\:idA').position().left,
position_width = $('#j_idt7\\:idA').width(),
position_height = $('#j_idt7\\:idA').height(),
gen_box = null,
i = 1;
console.log( 'Top Image: ' + position_top + 'px');
console.log( 'Left Image: ' + position_left + 'px');
console.log( 'Width Image : ' + position_width + 'px');
console.log( 'Height Image : ' + position_height + 'px');
main_content.selectable({
start: function(e) {
x_begin = e.pageX,
y_begin = e.pageY;
},
stop: function(e) {
x_end = e.pageX,
y_end = e.pageY;
if(x_end > position_left + position_width )
return;
if( x_end - x_begin >= 1 ) {
width = x_end - x_begin,
height = y_end - y_begin;
} else {
width = x_begin - x_end,
height = y_end - y_begin;
var drag_left = true;
}
if(width==0 & height==0)
{return;}
$(this).append('<div class="gen_box_' + i + '">Test</div>');
gen_box = $('.gen_box_' + i);
$(gen_box).css({
'background' : '#006600',
'width' : width,
'height' : height,
'position' : 'absolute',
'left' : x_begin,
'text-align' : 'center',
'vertical-align': 'middle',
'Opacity' : '0.3',
'top' : y_begin
})
.draggable({ grid: [1, 1] })
.resizable({
start: function( event, ui ){
var x = event.clientX;
var y = event.clientY;
if(x!=13)
console.log('Test');
}
});
drag_left ? $(gen_box).offset({ left: x_end, top: y_begin }) : false;
i++;
}});
});
</script>
Once I put "==" or "!=" in the part :
if(x!=13)
console.log('Test');
It works without any problem, once I change it by "<" or ">" I got an error in the console saying :
Uncaught SyntaxError: Unexpected token ;
This is really weird !! Any help please ?
You can find escape html code here.
escape html
Use an editor that is designed for writing code.
It looks like the one you're using (which is it?) is ill-suited to writing code: it seems to be HTML encoding your tokens: & is becoming & throughout, and so on.
Likely the same is happening with < and >: they are being HTML-encoded to < and > respectively, and the semicolon in that replacement is causing your syntax error.

Jquery plugin using second instance's options

I have written a Jquery Pagination plugin that works great with just one instance of the plugin. When I try to use two instances, the first instance ignores its given options and uses the second instance's options. I know this because the two sections both start out with the defined items per page, but when you navigate to another 'page' in the pagination, it reverts to the second instance's itemsPerPage - 2.
My guess is the second time this plugin is called, it is overwriting $.pagination's options, so when either pagination goes to a new page, it uses the overwritten options.
Here's the plugin:
/* Jquery Pagination */
(function($){
$.pagination = {
defaultOptions : {
itemsPerPage : 5,
startPage : 1,
showNextPrev : true,
navigationPosition : 'before',
paginationClass : 'pagination',
paginationItemClass : 'paginationItem',
paginationItemActiveClass : 'active',
nextClass : 'next',
nextText : 'Next',
prevClass : 'prev',
prevText : 'Prev',
}
}
$.fn.extend({
pagination : function(newOptions){
var options = $.extend($.pagination.defaultOptions, newOptions),
itemsToPaginate = $(this),
itemsToPaginateContainer = itemsToPaginate.eq(0).parent(),
paginationWrapper = "<div class='" + options.paginationClass + "'></div>",
paginationControls = '',
pagination,
numberOfPages,
showPage = function(goToPage){
var page = (typeof goToPage === 'number') ? goToPage : goToPage.attr('href').replace('#page', ''),
itemRangeEnd = page * options.itemsPerPage
itemRangeStart = itemRangeEnd - options.itemsPerPage;
$( '.' + options.paginationItemClass, pagination).removeClass(options.paginationItemActiveClass);
if (typeof goToPage === 'number')
pagination.find('.' + options.paginationItemClass).eq(goToPage-1).addClass(options.paginationItemActiveClass);
else
goToPage.addClass(options.paginationItemActiveClass);
itemsToPaginate.hide().slice(itemRangeStart, itemRangeEnd).show();
},
createPagination = (function(){
// Add pagination element to DOM
switch(options.navigationPosition.toLowerCase()){
/*
// TODO: Create ability to insert pagination after or before & after
case 'both':
itemsToPaginateContainer.before(paginationWrapper);
itemsToPaginateContainer.after(paginationWrapper);
break;
case 'after':
itemsToPaginateContainer.after(paginationWrapper);
break;
*/
default:
itemsToPaginateContainer.before(paginationWrapper);
break;
}
// Selecting pagination element
pagination = itemsToPaginateContainer.siblings('.' + options.paginationClass);
// Count how many pages to make
numberOfPages = Math.ceil( itemsToPaginate.length / options.itemsPerPage );
// Insert controls into pagination element
if(options.showNextPrev) paginationControls += "<a href='#' class='" + options.prevClass + "'>" + options.prevText + "</a>";
for (var i = 1; i <= numberOfPages; i++) {
paginationControls += "<a href='#page" + i + "' class='" + options.paginationItemClass + "'>" + i + "</a>";
}
if(options.showNextPrev) paginationControls += "<a href='#' class='" + options.nextClass + "'>" + options.nextText + "</a>";
(numberOfPages !== 1) ? pagination.html(paginationControls) : pagination.remove() ;
}()),
bindUIEvents = (function(){
pagination.find('.' + options.paginationItemClass + ':not(.' + options.nextClass + '):not(.' + options.prevClass + ')').on('click', function(e){
e.preventDefault();
showPage( $(this) );
});
pagination.find('.' + options.prevClass).on('click', function(){
var prevPageIdx = pagination.find('.' + options.paginationItemActiveClass).index() - 1;
// console.log(prevPageIdx);
if(prevPageIdx < 1)
showPage(numberOfPages);
else
showPage(prevPageIdx);
});
pagination.find('.' + options.nextClass).on('click', function(){
var nextPageIdx = pagination.find('.' + options.paginationItemActiveClass).index() + 1;
if(nextPageIdx > numberOfPages)
showPage(1);
else
showPage(nextPageIdx);
});
}());
showPage(options.startPage);
return this;
}
});
})(jQuery);
JSFiddle
Any idea why each instance of this plugin doesn't just use its own options? How would I need to structure a plugin to encapsulate and protect their own options? Thanks!
Change
var options = $.extend($.pagination.defaultOptions, newOptions),
To
var options = $.extend({}, $.pagination.defaultOptions, newOptions),
Demo
Reason is you are providing the target as defaultOption while using the syntax jQuery.extend( target [, object1 ] [, objectN ]

How to populate new html pages with xml data in jQuery

I have an RSS reader that fetches events with ajax. I want the user to be able to click the link of the event and have it transition to a new page with the details. Here is an example I found: http://jsfiddle.net/hellosze/t22QP/ I am have trouble understanding what is happening since I am rather new to jQuery so I was hoping someone code direct me as to what is happening. Thanks!
Here is how I extract the xml data and display it to a main page:
$.ajax({
type: 'GET',
url: 'categoryURL',
dataType: 'xml',
success: function (xml) {
var data = [];
$(xml).find("item:lt(40)").each(function () {
var dateText = $(this).find("Date").text().toString();
var eventDate = moment(dateText,"YYYY-MM-DD");
var title = $(this).find("title").text();
var region = dateText.substr(8).toUpperCase();
if (region.length < 3) { region = "ALL"; }
var description = $(this).find("description").text();
var dateDisplay = description.substr(0, description.indexOf(",")+6); //Parsed DATE from description
if (dateDisplay.length > 35) { dateDisplay = "See event for details"; }
//var locationdisplay = description.substr(description.indexOf(",")+6,4); //Parsed the location from description
var category = $(this).find("category").text();
var linkUrl = $(this).find("link").text();
var displayTitle = "<a href='" + linkUrl + "' target='_blank'>" + title + "</a>"
var item = {title: displayTitle, DateDecription: dateDisplay, Date: new Date(eventDate), Region: region,}
data.push(item);
// $('#feedContainer').append('<h3>'+displaytitle+'</h3><p>'+"Event Date: "+descriptdisplay+'</p><p>'+"Location: "+region+'</p');
}); //END .each()
data.sort(function (a, b) {
a = new Date(a.Date);
b = new Date(b.Date);
return a>b ? -1 : a<b ? 1 : 0;
});
$.each(data, function (index, item) {
$('#feedContainer').append('<h3>' + item.title + '</h3><p>' + "Event Date: " + item.DateDecription + '</p><p>' + "Location: " + item.Region + '</p');
});
} //END success fn
});
});

Replacing part of innerHTML text of a html select option field within multiple select does not work

THE FUNCTION
The SelectMultiple function comes up with a pop-up div with checkboxes in it.
The checkboxes are built equally to select options and added click event to build up
an array.
Beacuse there are many select menus on the page there is built a filterstack object to make the distinction per select menu name.
THE AIM AND THE PROBLEM
When a checkbox clicked the innerHTML (not the option value) text of option will be shown in the very first option field of referred select menu with comma separation, so far works.
On checkbox un-check should the text removed by javascripts replace function, but it not works.
NOTE 1:
Checkbox events building at this moment a string. Before this I've tried an array and did not worked too.
NOTE 2:
Tested on Firefox.
var filterstack = {};
var objSelected = {};
function SelectMultiple(field, isAction, paneId) {
//the first paramater might be "this" or the field id.
if (typeof field == "string")
field = $(field);
field.onchange = function () {};
objSelected["" + field.name + ""] = new Array();
var popdiv = document.createElement('DIV');
$(popdiv).setStyle({
backgroundColor: '#fff',
'z-index': '999999999991',
'margin': '-24px -2px',
'width': field.parentNode.offsetWidth + 'px',
'height': field.options.length * 20 + 31 + 'px',
'position': 'absolute',
'display': 'block'
});
popdiv.id = "" + field.name + "";
var selArr = new Array();
var selinnerHTML = "";
for (var i = 0; i < field.options.length; i++) {
var innerdiv = document.createElement('DIV');
$(innerdiv).setStyle({
'width': 'auto',
'position': 'relative'
});
var optionlabel = document.createElement('LABEL');
optionlabel.innerHTML = field.options[i].innerHTML;
$(optionlabel).setStyle({
'width': field.offsetWidth - 25 + 'px'
});
innerdiv.appendChild(optionlabel);
var optionfield = document.createElement('INPUT');
var fieldName = field.name + '[' + field.options[i].value + ']';
optionfield.type = 'checkbox';
optionfield.id = fieldName; //p.vendors_id[0]
optionfield.name = fieldName;
optionfield.toreplace = field.options[i].innerHTML.toString();
if (filterstack["" + fieldName + ""] &&
objSelected["" + field.name + ""]) {
optionfield.checked = true;
selArr.push(field.options[i].value);
if (!(selinnerHTML.match('/' + optionfield.toreplace + '/gi')))
selinnerHTML += optionfield.toreplace + ', ';
} else {
optionfield.checked = false;
selinnerHTML.replace('/' + optionfield.toreplace + '/gi', '');
}
optionfield.value = field.options[i].value;
$(optionfield).setStyle({
'width': '10px',
'display': 'inline'
});
optionfield.onclick = function (e) {
var el = (e) ? e.target : ((window.event.srcElement) ? window.event.srcElement : null);
var selArr = objSelected["" + field.name + ""];
if (el.checked) {
selArr.push(el.value);
filterstack["" + field.name + ""] = selArr;
if (!(selinnerHTML.match('/' + el.toreplace + '/gi')))
selinnerHTML += el.toreplace + ', ';
} else {
// .replace DOES NOT WORK
if ((selinnerHTML.match('/' + el.toreplace + '/gi')))
selinnerHTML.replace('/' + el.toreplace + '/gi', '');
field.options[field.selectedIndex].innerHTML = selinnerHTML;
for (var i = 0; i < selArr.length; i++) {
if (!selArr[i].checked && selArr[i] == el.value) {
selArr.splice(i, 1);
break;
}
}
filterstack["" + field.name + ""] = selArr;
}
}; //optionfield.onclick
//ignore empty values
if (optionfield.value != "")
innerdiv.appendChild(optionfield);
popdiv.appendChild(innerdiv);
} //for
field.options[0].innerHTML = selinnerHTML;
objSelected["" + field.name + ""] = selArr;
filterstack["" + field.name + ""] = selArr;
var ok = document.createElement('INPUT');
ok.type = 'button';
ok.value = 'OK';
$(ok).setStyle({
'width': '55px',
'margin': '5px 0px 0px 7px',
'text-align': 'center'
});
ok.onclick = function (el) {
postFilter(null, null, isAction + '/', field.name + '/', filterstack["" + field.name + ""] + '/', paneId);
field.parentNode.removeChild(popdiv);
};
var cancel = document.createElement('INPUT');
cancel.type = 'button';
cancel.value = 'Cancel';
$(cancel).setStyle({
'width': '55px',
'margin': '0',
'text-align': 'center',
'display': 'inline'
});
cancel.onclick = function (el) {
field.parentNode.removeChild(popdiv);
};
popdiv.appendChild(ok);
popdiv.appendChild(cancel);
field.parentNode.appendChild(popdiv);
}​
Using innerHTML is not the way to go for <option> elements. Use the option's text property instead.

Categories