How can i save tasks in dhtmlx gantt? - javascript

I used dhtmlx for chart gantt, I succeed in saving tasks in the data base, the problem is that when I add a new task there is no change in the chart,
for example if I add a new task with 4 days as duration it appears just one cell not four ones and also for the other properties.
Here the code of adding a new task :
<script type="text/javascript">
gantt.init("gantt_here");
gantt.attachEvent("onLightboxSave", function(id, task, is_new){
mnth = ("0" + (task.start_date.getMonth()+1)).slice(-2),
day = ("0" + task.start_date.getDate()).slice(-2);
mnth = ("0" + (task.end_date.getMonth()+1)).slice(-2),
day = ("0" + task.end_date.getDate()).slice(-2);
$.post("Control",{id:task.id,duration:task.duration,text:task.text,start_date:[ day,mnth, task.start_date.getFullYear() ].join("-").toString()},function(data){
alert(data);
}) ;
gantt.hideLightbox();
});
</script>

Try returning 'true' from onLightboxSave handler http://docs.dhtmlx.com/gantt/api__gantt_onlightboxsave_event.html
If you return 'false' or 'undefined' (as in your case), the form stays opened and the form values are not applied to the client-side.
Returning 'true' will save values and close the form, so you won't need to call hideLightbox manually
gantt.attachEvent("onLightboxSave", function(id, task, is_new){
var dateToStr = gantt.date.date_to_str("%d-%m-%Y");
$.post("Control",{
id:task.id,
duration:task.duration,
text:task.text,
start_date:dateToStr(task.start_date)
},function(data){
alert(data);
}) ;
return true;
});

Related

How to automatically close window created by Google Script Content Service/HTML Service?

I have a doGet(e) function in Google Script that writes to a spreadsheet, then returns a simple "success" message created with Content Service. My question is, is there a way to automatically close the tab/window created by this message? The user will be "approving" different items when they write to the spreadsheet, and it might get annoying to approve several items in a row using this function, then have to close each successive tab the function creates.
Here's the GS:
function doGet(e) {
var id = e.parameter.id;
var fundnumber = e.parameter.fundnumber;
var date = Utilities.formatDate(new Date(), "America/New_York", "MM/dd/yyyy");
var sh = SpreadsheetApp.openById("12jWGJWHCLoiLVoA0TlBQ0QgOMxBU9gVj9HQQveiNg0w").getSheetByName("Purchase Order Meta");
var data = sh.getDataRange().getValues();
for(n=0;n<data.length;++n){
if( data[n][1].toString().match(id)==id ){
data[n][8] = 'Approved by Linda on ' + date;
data[n][16] = 'Approved by Linda on ' + date + '. Awaiting order from Trish.';
data[n][13] = fundnumber
};
sh.getRange(1,1,data.length,data[0].length).setValues(data); // write back to the sheet
}
return ContentService.createTextOutput("success");
}
My understanding is that I have to return something either with Content Service or HTML Service in order to write a doGet. I've tried using HTML Service and add JS to the page to close the window, but it doesn't seem to work. :\
Using the HTMLService output, you can close a popup or HTML page by wrapping google.script.host.close() in a timeout function, like so:
setTimeout( function() { google.script.host.close(); }, 3000);
Change your return to:
var output = "<body><p>Success!</p><script>setTimeout( function() { google.script.host.close(); }, 3000);</script></body>"
return HtmlService.createHtmlOutput(output);

UI Datepicker: choosing date overwrites existing settings

I am trying to write a custom datepicker, where the default drop downs for months and year ranges (enabled through changeMonth and changeYear options) are replaced by custom drop downs. It is something like this:
Fiddle: http://jsfiddle.net/gGV3v/
$("#myId").datepicker({
...default settings...
beforeShow: function() {
...here I replace the default dropdowns by custom dropdowns...
...something like...
$(".ui-datepicker-month").replaceWith("#custom-html-block");
$(".ui-datepicker-year").replaceWith("#another-custom-html-block");
}
});
On choosing either month or year from the custom dropdowns, I want to change the date in the view accordingly. So I construct the date string from the current month and year (the date for the new month/year combo defaults to 1 here), and I call
$("#custom-html-block .custom-dropdown-option").on("click",function() {
...construct newDateString...
$("#myId").datepicker("setDate",newDateString)
});
$("#another-custom-html-block .custom-dropdown-option").on("click",function() {
...construct newDateString...
$("#myId").datepicker("setDate",newDateString)
});
I want the span with text foo to remain intact when setting the new date programmatically on clicking it.
The problem is: it wipes off the custom drop downs and the default ones come again. I tried to do things like this:
$("#myId").datepicker($.extend({setDate: newDateString},oldSettings))
But it still doesn't work. How do I make this work?
You can set the value of the function $.datepicker._generateMonthYearHeader, the downside it that will be global for all datepicker in the page.
The sample is below:
$.datepicker._generateMonthYearHeader = function(inst, drawMonth, drawYear, minDate, maxDate,
secondary, monthNames, monthNamesShort) {
var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear,
changeMonth = this._get(inst, "changeMonth"),
changeYear = this._get(inst, "changeYear"),
showMonthAfterYear = this._get(inst, "showMonthAfterYear"),
html = "<div class='ui-datepicker-title'>",
monthHtml = "";
// year selection
if ( !inst.yearshtml ) {
inst.yearshtml = "";
if (secondary || !changeYear) {
html += "<span class='ui-datepicker-year'>" + drawYear + "</span>";
} else {
// determine range of years to display
years = this._get(inst, "yearRange").split(":");
thisYear = new Date().getFullYear();
determineYear = function(value) {
var year = (value.match(/c[+\-].*/) ? drawYear + parseInt(value.substring(1), 10) :
(value.match(/[+\-].*/) ? thisYear + parseInt(value, 10) :
parseInt(value, 10)));
return (isNaN(year) ? thisYear : year);
};
year = determineYear(years[0]);
endYear = Math.max(year, determineYear(years[1] || ""));
year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
inst.yearshtml += "<span class = 'dummy'>Foo</span> <select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>"
for (; year <= endYear; year++) {
inst.yearshtml += "<option value='" + year + "'" +
(year === drawYear ? " selected='selected'" : "") +
">" + year + "</option>";
}
inst.yearshtml += "</select>";
html += inst.yearshtml;
inst.yearshtml = null;
}
}
And your fiddle: http://jsfiddle.net/gGV3v/2/
UPDATE:
Without the buttons, and using a better approach, now you have control of all generated HTML:
var oldGenerateHTML = $.datepicker._generateHTML;
function newGenerateHTML(inst) {
var html = oldGenerateHTML.call(this, inst);
var $html = $(html);
$html.find('[data-handler=prev]').remove();
$html.find('[data-handler=next]').remove();
$html.find('[data-handler=selectMonth]').replaceWith('<span class="dummy">Foo</span>');
return $html;
}
$.datepicker._generateHTML = newGenerateHTML;
Fiddle also updated: http://jsfiddle.net/gGV3v/4/
In general this is why extend sucks. The parent (in your case datepicker) doesn't know anything about childs (your custom html). Everytime it refresh the view, your changes are lost. This problem is usually solved using composition. The goal is to create your own widget (I think that was the term in jQuery) that have datepicker as a local variable and to control _generateMonthYearHeader function calls. It's easy to say in theory but in practice (specially case with jQuery) is hard to achive. Easier solution will be to proxy the function.
//preserve _generateHTML because after it finish, html is visible and .ui-datepicker-month and .ui-datepicker-year are in dom tree
fn = $.datepicker._generateHTML; //preserve original function
$.datepicker._generateHTML = function(inst) {
//call original function
fn.call(this, inst);
//do custom changes
//you'll need better selectors in case of multiple datepicker instances
$(".ui-datepicker-month").replaceWith("#custom-html-block");
$(".ui-datepicker-year").replaceWith("#another-custom-html-block");
}
Personally I dislike this approach (I prefer composition as I said) but in your case it'll be easier to implement. The reason its easier is because generateMonthYearHeader is called from many different functions.
P.S. Not tested

How to display JS values on my HTML page

I'm trying to get three different dynamic timezone clocks on my site. i've got the following js code which i found on this site (saved as myClocks.js and included on the header of my html site):
var clock1 = new Date();
var clock2 = new Date();
var clock3 = new Date();
clock2.setHours(clock2.getHours() + 3);
clock3.setHours(clock3.getHours() - 5);
clock1.getUTCHours();
clock1.getUTCMinutes();
clock1.getUTCSeconds();
clock2.getUTCHours();
clock2.getUTCMinutes();
clock2.getUTCSeconds();
clock3.getUTCHours();
clock3.getUTCMinutes();
clock3.getUTCSeconds();
How do I code the "display" to show it anywhere I want on my HTML page? For example as an id called clocks, to look like the following:
New York: 02:12:02 Paris: 17:01:24 Moscow: 22:23:42
Many thanks in advance.
<html><head></head><body>
<script language="javascript">
ourDate = new Date();
document.write("The time and date at your computer's location is: "
+ ourDate.toLocaleString()
+ ".<br/>");
document.write("The time zone offset between local time and GMT is "
+ ourDate.getTimezoneOffset()
+ " minutes.<br/>");
document.write("The time and date (GMT) is: "
+ ourDate.toGMTString()
+ ".<br/>");
</script>
</body></html>
innerHTML is what you need. Try something like:
window.onload = function(){ // It is important to wait till DOM is ready!
var clocks_str = clock3.getUTCHours()+" "+ clock3.getUTCMinutes()+" "+clock3.getUTCSeconds();
document.getElementById("clocks").innerHTML = clocks_str ;
}
And if you want it dynamic , use setInterval method , like this:
var clocks_interval;
var clocks_box;
window.onload = startClocks;
function startClocks(){
clocks_box = document.getElementById("clocks");
clocks_interval = setInterval(updateClocks , 1000); // 1000 means 1 second
}
function updateClocks (){
var clocks_str = clock3.getUTCHours()+" "+ clock3.getUTCMinutes()+" "+clock3.getUTCSeconds();
clocks_box.innerHTML = clocks_str ;
}
You can create a div or other HTML and use "innerHTML".
document.getElementById("clocks").innerHTML = clock1.getUTCHours();

getting jquery to trigger onclick off a class

I do apologize if this is an easy fix, I'm a tad new to jquery. To start I don't think that it is my initial call that is messing up because if I put a simple alert function in than it will work fine onclick, basically when this <li> is clicked on, jquery trigers an ajax to php function sending the class of the <li> to a php script and back, opening an alert with the result. As far as I can tell it should be working, but again my knowledge is rather limited. Any change anyone can take a look at what I have and see if you can clean it up at all, currently nothing happens onclick, no errors even appear in the console. But I imagine that even my ajax call is wrong. Any ideas why nothing happens on click?
HTML:
<li title = "Previous Month" id = "changeMonthBack" class = "<?php echo date('n'); ?>"><img src="images/leftArrow.gif" width="54" height="45" alt="previous month"></li>
jQuery/javascript:
//javascript document
$(document).ready(function(){
//need to do an onclick for getting the new month(previous)
$(".changeMonthBack").click(function(){
function calendar(){
//set the id for php
var identifier = 1;
//get the class to use for month
var str = document.getElementById("changeMonthBack").class;
//get the month number
//if the month is 1, we obviously need it to be 12
if str == 1{
var month = 12;
}
else{
var month = str - 1;
}
$.post("redraw.php"),{
identifier: identifier,
month: month
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
};
})//end function 1
});
There are multiple problems with the script.
1. As Aesthete suggested the selector should be an id selector #changeMonthBack
2. You are creating a closure method called calendar but never called it
3. There were multiple syntax error (Use a javascript editor like spket)
You are creating a function called calendar but never calls it.
$(document).ready(function() {
// need to do an onclick for getting the new month(previous)
$("#changeMonthBack").click(function() {
// set the id for php
var identifier = 1;
// get the class to use for month
var str = parseInt($(this).attr('class'),10);
// get the month number
// if the month is 1, we obviously need it to be 12
if (str == 1) {
var month = 12;
} else {
var month = str - 1;
}
$.post("redraw.php", {
identifier : identifier,
month : month
},
function(data, status) {
alert("Data: " + data + "\nStatus: "
+ status);
});
});
});

Using jQuery/JS, can I "tie" together a JS object's property directly to the value of a form input element?

I'm building out an online reservation system for a pet-boarding business in my city and I've hit a wall as to how to efficiently carry out this specific functionality.
Quick gist of the user process...
Some preliminary info is given (client info, pet info, etc etc).
User chooses 2 dates; the check-in and check-out days.
The program calculates the number of days the client is staying and each day is thrown into a constructor for class "Day". A ... block is generated for each day and displayed to the user. It also might be worth noting that all of the Day objects are stored in an array which is then contained in the mama class "ReservationData"...which besides the Day-array also holds some meta-data pertaining to the reservation itself.
Anyway, my problem is that once the 'dayBlocks' are listed & displayed to the user, the user must then be able to go and check individual "extras" that they want for their pet on that specific day.
So I've broken it down so that {ReservationData} <--(has an array of)-- {Days} <--(has an array of)-- {Extras}. There are 14 extra services to choose from, so for each day displayed there is a simple list of checkboxes and labels.
Ideally, I want it setup so that when a checkbox is checked by the user, it directly & immediately alters its corresponding variable within the reservationDataDaysExtraDeepArray accordingly. The C-programmer in me wants to tie a pointer to each checkbox, but I'm (at least I think) pretty sure that's not doable with jQuery.
Although I think I explained it pretty clearly, here's some of the code:
//Day Object/Class
function day(_date, _daynum) {
this.date = new Date(_date);
this.dayNum = _daynum;
this.dayExtras = {
'YH': false, //<--- How can I directly manipulate
'PP': false, //<--- all of these guys via user-control
'EE': false, //<--- of corresponding/assigned
'ST': false, //<--- checkboxes?
'PT': false,
'TT15': false,
'TT30': false,
'TT45': false,
'DC': false //--- Or can I? :/
};
console.log("Day object created with date of " + day.date + " and day-number of " + day.dayNum + ".");
this.getDayNum = function() { return this.dayNum; }
this.getDayDate = function() { return this.date; }
}
This is my first question on this site, but I did a lot of searching and am still lost...thanks guys!
Assuming the name of your checkboxes correspond to the keys in your dayExtras object something like this would do..
//Day Object/Class
function day(_date, _daynum) {
this.date = new Date(_date);
this.dayNum = _daynum;
this.dayExtras = {
'YH': false, //<--- How can I directly manipulate
'PP': false, //<--- all of these guys via user-control
'EE': false, //<--- of corresponding/assigned
'ST': false, //<--- checkboxes?
'PT': false,
'TT15': false,
'TT30': false,
'TT45': false,
'DC': false //--- Or can I? :/
};
console.log("Day object created with date of " + day.date + " and day-number of "+day.dayNum+".");
this.getDayNum = function() { return this.dayNum; }
this.getDayDate = function() { return this.date; }
this.setDayExtras = function (key,val) {
if(key in this.dayExtras){
this.dayExtras[key] = val;
}
}
}
var myDay = new day(null,null);
$(document).on('change','#myForm input[type="checkbox"]', function () {
myDay.setDayExtras(this.name,this.checked);
});
Got it working, thanks for pointing me in the right direction guys!
function saveExtra(me) {
var extraName = me.attr('name');
var extraVal = me.val();
(reservationData[extraName]).dayExtras[extraVal] = me.prop('checked');
for (key in reservationData) {
(reservationData[key]).dump(); //Day data-dump method.
}
}
this.generateExtrasGrid = function() {
var fieldName = "day" + this.dayNum + "";
var exGrid = "";
exGrid += "<form class='extrasGrid' id='" + this.dayNum + "'>";
exGrid += "<input type='checkbox' class='extra' name='" + fieldName + "' value='YH' onclick='saveExtra($(this))' />";............
exGrid += "</form>";
return exGrid;
}​

Categories