Showing Events on a Datepicker with Server-side data - jquery-ui

I have been busy creating a solution to a client that has proven to be a bit more difficult than I thought it would be. I am using the jQuery Datepicker widget to display calendar events (monthly view) from server-side code. Every thing in the following code works EXCEPT the CSS. It is not changing anything and it seems I've tried everything in the world.
A Calendar is shown in month-view on page-load (MVC) and if a user has events the day should have a different background-color. Also, when the user changes month-to-month, the same logic happens (ajax call to server). Again, this all is working well. My directive to change the background color will not.
<script type="text/javascript">
$(document).ready(function () {
$.expr[":"].exactly = function (el, i, m) {
var s = m[3];
if (!s) return false;
return eval("/^" + s + "$/i").test($(el).text());
};
var currentYear = (new Date).getFullYear();
var currentMonth = (new Date).getMonth();
function getTheData(year, month) {
var theYear = year;
var theMonth = month;
//alert(theYear + ", " + theMonth);
$.post("GetMeSomeData", { year: theYear, month: theMonth }, function(data) {
//cycle through the dates and address the CSS appropriately
var i = 0;
for (i = 0; i < data.length; i++) {
$('.ui-datepicker-calendar td a:exactly(' + data[i]['d'] + ')')
.css({ backgroundColor: 'blue' });
}
});
}
$('#date').datepicker({
inline: true,
beforeShowDay: getTheData(currentYear, currentMonth),
onSelect: function (dateText, inst) {
Date.prototype.toString = function () { return isNaN(this) ? 'NaN' : [this.getDate(), this.getMonth(), this.getFullYear()].join('/'); };
d = new Date(dateText);
//alert(d.getDate() + ", " + d.getFullYear());
getTheData(d.getFullYear(), d.getDate());
},
onChangeMonthYear: function (year, month, inst) {
//alert(year + ", " + month);
getTheData(year, month);
}
});
});
</script>

Related

Get term for selected autocomplete when multiple are on one page

I have a page where I am adding jquery-ui autocompletes dynamically
My .autocomplete() code includes a $.getJSON('my_url', my_payload) where, in my_payload,' I am trying to send the request.term (what I typed into the jqueryui textbox) as well as the id of the jquery ui text box.
The problem is, for all the dynamically added textboxes, they were just picking up the term and id of the original autocomplete.
I managed to find a way to get the id of the added (not original) autocomplete by wrapping the autocomplete in a function that has the added field passed in as a parameter, but because the 'term' is in the request, which comes from .autocomplete, I do not know how to get this for the new ones.
https://jsfiddle.net/amchugh89/1L8jvea5/4/
//=======dynamic formset script from https://medium.com/all-about-
django/adding-forms-dynamically-to-a-django-formset-375f1090c2b0======
function updateElementIndex(el, prefix, ndx) {
var id_regex = new RegExp('(' + prefix + '-\\d+)');
var replacement = prefix + '-' + ndx;
if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement));
if (el.id) el.id = el.id.replace(id_regex, replacement);
if (el.name) el.name = el.name.replace(id_regex, replacement);
}
function cloneMore(selector, prefix) {
var newElement = $(selector).clone(true);
var total = $('#id_' + prefix + '-TOTAL_FORMS').val();
newElement.find(':input:not([type=button]):not([type=submit]):not([type=reset])').each(function() {
if ($(this).attr('name')){
var name = $(this).attr('name').replace('-' + (total-1) + '-', '-' + total + '-');
var id = 'id_' + name;
$(this).attr({'name': name, 'id': id}).val('').removeAttr('checked');
if($(this).attr('id').includes('gl')){
console.log($(this).attr('id'))
make_autocomplete($(this))
}
}
});
newElement.find('label').each(function() {
var forValue = $(this).attr('for');
if (forValue) {
forValue = forValue.replace('-' + (total-1) + '-', '-' + total + '-');
$(this).attr({'for': forValue});
}
});
total++;
$('#id_' + prefix + '-TOTAL_FORMS').val(total);
$(selector).after(newElement);
var conditionRow = $('.form-row:not(:last)');
conditionRow.find('.btn.add-form-row')
.removeClass('btn-success').addClass('btn-danger')
.removeClass('add-form-row').addClass('remove-form-row')
.html('<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>');
return false;
}
function deleteForm(prefix, btn) {
var total = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
if (total > 1){
btn.closest('.form-row').remove();
var forms = $('.form-row');
$('#id_' + prefix + '-TOTAL_FORMS').val(forms.length);
for (var i=0, formCount=forms.length; i<formCount; i++) {
$(forms.get(i)).find(':input').each(function() {
updateElementIndex(this, prefix, i);
});
}
}
return false;
}
$(document).on('click', '.add-form-row', function(e){
e.preventDefault();
cloneMore('.form-row:last', 'form');
return false;
});
$(document).on('click', '.remove-form-row', function(e){
e.preventDefault();
deleteForm('form', $(this));
return false;
});
//====================
//AUTOCOMPLETE==(that allows for multiple ACs
https://stackoverflow.com/questions/24656589/using-jquery-ui-autocomplete-
with-multiple-input-fields)===================================
function make_autocomplete(ee) {
ee.on("focus", function(){ //.autocomplete({
$(this).autocomplete({
minLength: 2,
source: function( request, response ) {
var term = request.term;
//with the formset, I want to get the row for which I am typing in the
'term'
var this_formset_row_autocomplete_id
=ee.attr('id');//$(this.element).prop("id");//
$(this).attr('id');
console.log(this_formset_row_autocomplete_id);
var corresponding_branch_html_id =
this_formset_row_autocomplete_id.replace('gl_account','branch');
var this_formset_row_branch_sym_id =
$('#'+corresponding_branch_html_id).val();
//console.log(corresponding_branch_html_id, this_formset_row_branch_sym_id)
var appended_data={term:term,
this_formset_row_branch_sym_id:this_formset_row_branch_sym_id};
console.log(appended_data);
$.getJSON( "{% url 'dashapp:account_autocomplete' %}", appended_data,
function( data,
status, xhr ) {
//cache[ term ] = data;
response( data );
});
}
});
});
}//end function make_autocomplete
var ee =$( ".account_autocomplete" )
make_autocomplete(ee)
//===============
You may want to try to make it more simple for testing. Something like:
function make_autocomplete(obj) {
obj.autocomplete({
minLength: 2,
source: function(req, resp) {
var myData = {
term: req.term,
original_form_branch_id: $(this).closest("form").attr("id"),
this_formset_row_branch_sym_id: $(this).closest(".row").find("select").val()
}
$.getJSON("myurl", myData, function(results) {
resp(results);
});
}
});
}
Fiddle: https://jsfiddle.net/Twisty/pywb9nhv/23/
This uses .closest() to gather details from the relative objects. Also I do not see any benefit to initializing Autocomplete on focus event.
If you would like further help, please provide Example Data that can be used in a working example.
Hope that helps a little.

Showing Page Loading Message in single application in jquery mobile

I am trying to show loading message ...... I am working on single page application in phonegag using jquery mobile.
$(document).delegate("#cartaxvalidityPage", "pageinit", function () {
$.mobile.showPageLoadingMsg();
createCarTaxValidPage();
$.mobile.hidePageLoadingMsg();
});
function createCarTaxValidPage() {
var buyerList = carHaatDatabaseParsed.BuyerList;
$("#buyer-listview").empty();
for (var i = 0; i < buyerList.length; i++) {
var listItem = $('<li> </li>');
var listAnc = $('<a> </a>');
var carImag = "<img " + "src='" + "data:image/jpg;base64," + buyerList[i].BuyerPhoto + "'/>";
var listHeader = $('<h3> ' + "Buyer Name: " + buyerList[i].BuyerName + ' </h3>');
var listParagraph = $('<p> Buyer Id: ' + buyerList[i].BuyerTaxId + ' </p>');
var listParagraphValidDate = $('<p> Tax Expire Date: ' + buyerList[i].CarValidityDate + '</p>');
listAnc.append(carImag);
listAnc.append(listHeader);
listAnc.append(listParagraph);
listAnc.append(listParagraphValidDate);
listItem.append(listAnc);
$("#buyer-listview").append(listItem);
}
$("#buyer-listview").listview("refresh");
}
It doesn't show any message.
.delegate is deprecated and replaced with .on.
$(document).on("pageinit", "#cartaxvalidityPage", function () { });
On pageinit event, use setTimeout to dela showing loading message.
setTimeout(function () {
$.mobile.loading("show");
}, 10);
Use $.mobile.loading("show") and $.mobile.loading("hide")
Demo

Jquery UI datepicker. Disable array of Dates

I have been trying to search for a solution to my Jquery ui datepicker problem and I'm having no luck. Here's what I'm trying to do...
I have an application where i'm doing some complex PHP to return a JSON array of dates that I want BLOCKED out of the Jquery UI Datepicker. I am returning this array:
["2013-03-14","2013-03-15","2013-03-16"]
Is there not a simple way to simply say: block these dates from the datepicker?
I've read the UI documentation and I see nothing that helps me. Anyone have any ideas?
You can use beforeShowDay to do this
The following example disables dates 14 March 2013 thru 16 March 2013
var array = ["2013-03-14","2013-03-15","2013-03-16"]
$('input').datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [ array.indexOf(string) == -1 ]
}
});
Demo: Fiddle
IE 8 doesn't have indexOf function, so I used jQuery inArray instead.
$('input').datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [$.inArray(string, array) == -1];
}
});
If you also want to block Sundays (or other days) as well as the array of dates, I use this code:
jQuery(function($){
var disabledDays = [
"27-4-2016", "25-12-2016", "26-12-2016",
"4-4-2017", "5-4-2017", "6-4-2017", "6-4-2016", "7-4-2017", "8-4-2017", "9-4-2017"
];
//replace these with the id's of your datepickers
$("#id-of-first-datepicker,#id-of-second-datepicker").datepicker({
beforeShowDay: function(date){
var day = date.getDay();
var string = jQuery.datepicker.formatDate('d-m-yy', date);
var isDisabled = ($.inArray(string, disabledDays) != -1);
//day != 0 disables all Sundays
return [day != 0 && !isDisabled];
}
});
});
$('input').datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [ array.indexOf(string) == -1 ]
}
});
beforeShowDate didn't work for me, so I went ahead and developed my own solution:
$('#embeded_calendar').datepicker({
minDate: date,
localToday:datePlusOne,
changeDate: true,
changeMonth: true,
changeYear: true,
yearRange: "-120:+1",
onSelect: function(selectedDateFormatted){
var selectedDate = $("#embeded_calendar").datepicker('getDate');
deactivateDates(selectedDate);
}
});
var excludedDates = [ "10-20-2017","10-21-2016", "11-21-2016"];
deactivateDates(new Date());
function deactivateDates(selectedDate){
setTimeout(function(){
var thisMonthExcludedDates = thisMonthDates(selectedDate);
thisMonthExcludedDates = getDaysfromDate(thisMonthExcludedDates);
var excludedTDs = page.find('td[data-handler="selectDay"]').filter(function(){
return $.inArray( $(this).text(), thisMonthExcludedDates) >= 0
});
excludedTDs.unbind('click').addClass('ui-datepicker-unselectable');
}, 10);
}
function thisMonthDates(date){
return $.grep( excludedDates, function( n){
var dateParts = n.split("-");
return dateParts[0] == date.getMonth() + 1 && dateParts[2] == date.getYear() + 1900;
});
}
function getDaysfromDate(datesArray){
return $.map( datesArray, function( n){
return n.split("-")[1];
});
}
For DD-MM-YY use this code:
var array = ["03-03-2017', '03-10-2017', '03-25-2017"]
$('#datepicker').datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
return [ array.indexOf(string) == -1 ]
}
});
function highlightDays(date) {
for (var i = 0; i < dates.length; i++) {
if (new Date(dates[i]).toString() == date.toString()) {
return [true, 'highlight'];
}
}
return [true, ''];
}
If you want to disable particular date(s) in jquery datepicker then here is the simple demo for you.
<script type="text/javascript">
var arrDisabledDates = {};
arrDisabledDates[new Date("08/28/2017")] = new Date("08/28/2017");
arrDisabledDates[new Date("12/23/2017")] = new Date("12/23/2017");
$(".datepicker").datepicker({
dateFormat: "dd/mm/yy",
beforeShowDay: function (date) {
var day = date.getDay(),
bDisable = arrDisabledDates[date];
if (bDisable)
return [false, "", ""]
}
});
</script>

on() doesn't work with live data using jQuery, how to?

i have some dynamic data that gets appended to a list and any links in that data doesnt seem to work.
i am using jquery 1.8.3 and on() should account for the live method, i think
setInterval(function () {
getNot();
}, 2000);
function getNot() {
var data = {
t1: 'test1',
t2: 'test2',
t3: 'test3'
};
var size = 0,
li = '';
$.each(data, function (k, v) {
li += '<li>' +
'<a href="#" class="add" data-listid="' + k + '">' +
'<h2>load data - ' + k + '</h2>' +
'</a>' +
'</li>';
size++;
});
var but = $('#not'),
ul = $('#not_ul');
but.find('span').text(size + ' Notifications');
ul.html(li);
ul.listview().listview("refresh");
}
// this doesn't seem to work
$('.add').on("click", function () {
var listId = $(this).data('listid');
console.log(listId);
return false;
});
see full example here
any ideas on this issue?
$('.add').on("click", function () {
You need to pass a selector to make on generate a delegate event:
$('#{containerId}').on("click", '.add', function () {
var listId = $(this).data('listid');
console.log(listId);
return false;
});
containerId should be the closest static element to the dynamic created .adds elements.

Google Calendar not displaying correct time

I have a Google Calendar for a school website I'm working on and am using the Google API to display the next five calendar events. One problem is that the time displays on a 24 hour clock instead of AM and PM, but that's not my main problem. The main problem is that while the events display the correct time on the website, when you click on the event to view it in the calendar event view, it will only display GMT time instead of Eastern Time. While logged into the Google account, the events display the right time zone, but whenever you view it while not logged in, it defaults to GMT.
I have tried changing it to another time zone and change it back, didn't fix it.
I also made sure all settings in both the calendar and the account were set to Eastern time zone, at least everywhere I could find it.
I've seen a lot of people with similar problems on Google sites using the ical or other feeds, but I haven't seen anyone with the problem using a code similar to mine.
The website is live: http://fletcheracademy.com. And here is the main javascript code that pulls it.
There's probably some details I'm missing, let me know if there's anything else you need to know. Thanks so much!
<script type="text/javascript">
google.load("gdata", "2.x");
function init() {
google.gdata.client.init(handleGDError);
loadDeveloperCalendar();
}
function loadDeveloperCalendar() {
loadCalendarByAddress('fletcheracademycalendar#gmail.com');
}
function padNumber(num) {
if (num <= 9) {
return "0" + num;
}
return num;
}
function loadCalendarByAddress(calendarAddress) {
var calendarUrl = 'https://www.google.com/calendar/feeds/' +
calendarAddress + '/public/full';
loadCalendar(calendarUrl);
}
function loadCalendar(calendarUrl) {
var service = new
google.gdata.calendar.CalendarService('gdata-js-client-samples-simple');
var query = new google.gdata.calendar.CalendarEventQuery(calendarUrl);
query.setOrderBy('starttime');
query.setSortOrder('ascending');
query.setFutureEvents(true);
query.setSingleEvents(true);
query.setMaxResults(5);
service.getEventsFeed(query, listEvents, handleGDError);
}
function handleGDError(e) {
document.getElementById('jsSourceFinal').setAttribute('style', 'display:none');
if (e instanceof Error) {
alert('Error at line ' + e.lineNumber + ' in ' + e.fileName + '\n' + 'Message: ' + e.message);
if (e.cause) {
var status = e.cause.status;
var statusText = e.cause.statusText;
alert('Root cause: HTTP error ' + status + ' with status text of: ' + statusText);
}
} else {
alert(e.toString());
}
}
function listEvents(feedRoot) {
var entries = feedRoot.feed.getEntries();
var eventDiv = document.getElementById('events');
if (eventDiv.childNodes.length > 0) {
eventDiv.removeChild(eventDiv.childNodes[0]);
}
var ul = document.createElement('ul');
//document.getElementById('calendarTitle').innerHTML =
// "Calendar: " + feedRoot.feed.title.$t;
var len = entries.length;
for (var i = 0; i < len; i++) {
var entry = entries[i];
var title = entry.getTitle().getText();
var startDateTime = null;
var startJSDate = null;
var times = entry.getTimes();
if (times.length > 0) {
startDateTime = times[0].getStartTime();
startJSDate = startDateTime.getDate();
}
var entryLinkHref = null;
if (entry.getHtmlLink() != null) {
entryLinkHref = entry.getHtmlLink().getHref();
}
var dateString = (startJSDate.getMonth() + 1) + "/" + startJSDate.getDate();
if (!startDateTime.isDateOnly()) {
dateString += " " + startJSDate.getHours() + ":" +
padNumber(startJSDate.getMinutes());
}
var li = document.createElement('li');
if (entryLinkHref != null) {
entryLink = document.createElement('a');
entryLink.setAttribute('href', entryLinkHref);
entryLink.appendChild(document.createTextNode(title));
li.appendChild(entryLink);
li.appendChild(document.createTextNode(' - ' + dateString));
} else {
li.appendChild(document.createTextNode(title + ' - ' + dateString));
}
ul.appendChild(li);
}
eventDiv.appendChild(ul);
}
google.setOnLoadCallback(init);
</script>
Try this!
Where you have:
var calendarUrl = 'https://www.google.com/calendar/feeds/' + calendarAddress + '/public/full';
you should add something like:
&ctz=Europe/Lisbon
Check here for the correct name of your timezone.

Resources