I have a page that shows me available dates in a database. It works well, but I have to refresh the page to get it to work. If I don't, the datepicker class just acts like a text box. Also, I need it to make an ajax call before it shows.
So to sum up, I go to '/tasks/new'. The page loads correctly. I click in the datepicker field and no calendar. No errors in the console. I refresh the page and it works. What do I need to do? My initial thought was that it needs to wait until the page is loaded, but that didn't seem to work (unless I did that wrong).
Here is the relevant code:
html
<input class="datepicker" id="task_start_date" name="task[start_date]" type="text">
tasks.js.coffee
full_days =[]
partial_days=[]
getDays = (date) ->
mmddyyyy = ("0" + (date.getMonth() + 1)).slice(-2) + "-" + ("0" + date.getDate()).slice(-2) + "-" + date.getFullYear()
jqxhr = $.get("/getdates/"+mmddyyyy, (data) ->
full_days = data['full']
partial_days = data['partial']
formatDays
return
)
formatDays = (date) ->
mmddyyyy = ("0" + (date.getMonth() + 1)).slice(-2) + "-" + ("0" + date.getDate()).slice(-2) + "-" + date.getFullYear()
if $.inArray(mmddyyyy, full_days) isnt -1
[
true
"full-day"
"Available"
]
else
if $.inArray(mmddyyyy, partial_days) isnt -1
[
true
"partial-day"
"Available"
]
else
[
false
""
"unAvailable"
]
# manipulate the json to make an array
availableHours = (day) ->
hours =[]
for index, hour_obj of day
hours.push hour_obj['hour']
return hours
$ ->
$('.datepicker').datepicker(
dateFormat: 'mm-dd-yy'
beforeShow: -> getDays
beforeShowDay: formatDays
onChangeMonthYear: (year, month, inst) ->
target = "#{month}-01-#{year}"
jqxhr = $.get("/getdates/"+target, (data) ->
full_days = data['full']
partial_days = data['partial']
formatDays
return
)
onSelect: (selectedDay) ->
box_id = $(this).attr('id')
box_id = "\##{(box_id.split '_')[1]}_hour"
new_list_items =[]
jqxhr2 = $.get('/gethours/'+selectedDay, (data)->
hours = availableHours(data)
for k,hour of hours
new_list_items.push '<option>'+hour+'</option>'
$(box_id).html('').append(new_list_items)
)
)
I found a way to fix my issues. It was all about when I called the functions and when I put the inital $ ->:
$ ->
full_days = []
partial_days = []
getDays = (date) ->
if (typeof date != 'string')
date = new Date()
date = ("0" + (date.getMonth() + 1)).slice(-2) + "-" + ("0" + date.getDate()).slice(-2) + "-" + date.getFullYear()
jqxhr = $.get("/getdates/" + date, (data) ->
full_days = data['full']
partial_days = data['partial']
formatDays
)
return
getDays()
formatDays = (date) ->
mmddyyyy = ("0" + (date.getMonth() + 1)).slice(-2) + "-" + ("0" + date.getDate()).slice(-2) + "-" + date.getFullYear()
if $.inArray(mmddyyyy, full_days) isnt -1
[
true
"full-day"
"Available"
]
else
if $.inArray(mmddyyyy, partial_days) isnt -1
[
true
"partial-day"
"Available"
]
else
[
false
""
"unAvailable"
]
# manipulate the json to make an array
availableHours = (day) ->
hours = []
for index, hour_obj of day
hours.push hour_obj['hour']
return hours
showdatepicker = ->
$('.datepicker').datepicker(
dateFormat: 'mm-dd-yy'
beforeShowDay: formatDays
onChangeMonthYear: (year, month, inst)->
target = "#{month}-01-#{year}"
getDays target
onSelect: (selectedDay) ->
getDays()
box_id = $(this).attr('id')
box_id = "\##{(box_id.split '_')[1]}_hour"
new_list_items = []
jqxhr2 = $.get('/gethours/' + selectedDay, (data)->
hours = availableHours(data)
for k,hour of hours
new_list_items.push '<option>' + hour + '</option>'
$(box_id).html('').append(new_list_items)
)
)
showdatepicker()
Related
Hi I have an events list that I want to show only upcoming events.
I want to remove past events table rows if date is less than todays date.
But I cannot get the associated row to remove?
Thanks
var date = jQuery('tr.Entries').find('td.event-date > a').text();
var dates = jQuery('tr.Entries').find('td.event-date > a').map(function() {
return jQuery(this).text();
}).get();
var currentDate = new Date();
currentDate = ("0" + currentDate.getDate()).slice(-2) + "/" + ("0" + (currentDate.getMonth() + 1)).slice(-2) + "/" + currentDate.getFullYear();
jQuery.each(dates, function(index, value) {
if (value < currentDate) {
console.log("true");
if (date === value) {
console.log("true");
jQuery(date).parent().remove(); //how to map table date to the row and delete the row?
}
}
});
I want to remove past events if date is less than todays date.
Do it in the initial filter itself
var currentDate = new Date();
currentDate = ( "0" + currentDate.getDate() ).slice(-2) + "/" + ( "0" + ( currentDate.getMonth() + 1 ) ).slice(-2) + "/" + currentDate.getFullYear();
jQuery( 'tr.Entries' ).find( 'td.event-date > a' ).each( function() {
var date = jQuery( this ).text();
if ( date < currentDate )
{
jQuery( this ).closest( ".event-date " ).remove(); //remove the parent which has lesser date `a`
}
});
I want to have the dateformat in this format: 2015-08-04T00:00:00Z.
so first year, month, day.
beforeShowDay: function (date) {
var dt = $.datepicker.formatDate('yy-mm-dd', date, "getDate")
return [$('#form_one3 > option:gt(0)[value="' + dt + 'T00:00:00Z"]').length != 0];
},
onSelect: function (dateText, inst) {
var dt = $.datepicker.formatDate('yy-mm-dd', dateText, "getDate")
alert(dt);
var hallo = $("#form_inp1").val() + 'T00:00:00Z';
alert(dateText);
alert(hallo);
//$("#form_inp1").datepicker("getDate");
//alert($("#form_inp1").formatDate('yy-mm-dd', dateText, "getDate")
},
But If I do an alert(dateText) I see the format as: 4-8-2015 and it has to be: 2015-08-04.
Thank you
If I try it like this:
onSelect: function (dateText, inst) {
dateText = dateText.split("-");
dateText = new Date('' + dateText[2] + '-' + dateText[1] + '-' + dateText[0] + '');
alert(dateText);
}
I get invalid date
So this var hallo = $("#form_inp1").val() + 'T00:00:00Z';
returns: 4-8-2015T00:00:00Z . But it has to be:2015-08-04T00:00:00Z.
Thank you
Quick fix is to change the date format using plain Javascript. This can be achieved by following script.
dt= dt.split("-");
dt = new Date('' + dt[2] + '-' + dt[1] + '-' + dt[0] + '');
to add zero in case the day, month and year is below 10, use following method.
function AddTrailingZero(i) {
if (i < 10) { i = "0" + i }; // add zero in front of numbers < 10
return i;
}
Let me know if you have any question related to the code snippet above.
i'm trying to use the gethours() method in javascript but it keeps returning military time. can someone please help me out fixing it so that it displays clock time? (1-12). Thank you so much!
// Reroute from the conf.js script
var chat = $( '.chat-output' ),
message = function ( message, userId ) {
var dt = new Date(),
time = dt.getHours() + ":" + dt.getMinutes(); // + ":" + dt.getSeconds();
return $( '<div class="chat-message color-' + users[userId] + '">' +
'<div class="chat-id color-' + users[userId] + '"></div>' +
'<div class="chat-user-message">' + message + '</div>' +
'<div class="chat-time">' + time + '</div>' +
'</div>' );
},
addText = function ( text ) {
// log.innerHTML += text;
// log.scrollTop = log.scrollHeight;
console.log( text );
},
addRemoteText = function ( userId, text ) {
// addText( '[' + userId + ']: ' + text+'<br>' );
chat.append( message( text, userId ) );
chat.scrollTop( chat.get( 0 ).scrollHeight );
};
function ampm(date){
var dt= date || new Date,
h= dt.getHours(),
m= dt.getMinutes(),
s= dt.getSeconds(),
ampm;
if(h>12){
h-= 12;
ampm= (h%12)? ' PM': ' AM';
}
else ampm= (h%12)? ' AM': ' PM';
m= m<10? '0'+m: m;
s= s<10? '0'+s: s;
return [h, m, s].join(':')+ampm;
}
ampm()
/* returned value: (String)
11:52:55 PM
*/
Something like this?
var dt = new Date();
var hours = dt.getHours();
var ampm = hours > 11 ? 'PM' : 'AM';
if (hours > 12) {
hours -= 12;
} else if (hours === 0) {
hours = 12;
}
var time = hours + ":" + dt.getMinutes() + ' ' + ampm;
Fiddle
Here's another version of formatting a time in 12 hour format:
// Returns formatted time for given Date object, or
// current system time if d is falsey.
function getTime(d) {
d = d || new Date();
var hrs = d.getHours();
var pad = function(n){return (n<10?'0':'')+ +n};
return pad(hrs%12 || 12) + ':' + pad(d.getMinutes()) + ' ' + (hrs<12? 'AM':'PM');
}
console.log(getTime(new Date(2014,2,24, 0, 5))); // 12:05 AM
console.log(getTime(new Date(2014,2,24,10,25))); // 10:25 AM
console.log(getTime(new Date(2014,2,24,20,15))); // 08:15 PM
Note that 24hr time is preferred in many cases to avoid anomalies like 12:00 AM (which is really neither AM or PM) and 12:00 AM being before 01:00 AM.
I'm using jquery's datepicker to select dates and I want to highlight some dates - but I'm experiencing a strange problem with beforeShowDay.
When the page loads it seems that the json data is loaded, but when I click into the input box and datepicker appears, nothing is highlighted. After I click on forward month or backward, data from a previous month is loaded (e.g. click in input -> datepicker appears -> no highlights -> click on next month -> data from prev month appears highlighted)...
I've googled a long time now, checked if data is loaded before everything, but somehow this behaviour is not changing. Both datepicker experience the same problem.
(jquery-ui datepicker 1.10.1, jquery 1.9.1)
I'm glad about every hint!
var resDates;
var done = false;
function markDate(date) {
var ret = [true, 'free'];
if (!done) {
$.ajax({
dataType: "json",
url: "modules/OutShop/getReservations.php",
data: {item_id: $("#item-id").val()},
async: false,
success: function (dates) {
resDates = dates;
done = true;
}
});
}
$.each(resDates, function(key, value) {
var d = (date.getFullYear() + "-" + ("0" + date.getMonth()).slice(-2) + "-" + ("0" + date.getDate()).slice(-2));
if (d == value["day"]) {
//$("body").append("d: " + d + ", v: " + value["day"] + ", s: " + value["status"] + " ");
//$("body").append("s: " + value["status"] + " ");
if (value["status"] == "1")
ret = [false, 'marked'];
else if (value["status"] == "2")
ret = [false, 'reserved'];
else
ret = [true, 'free'];
}
});
return ret;
}
$(document).ready(function() {
if (!done) {
$.ajax({
dataType: "json",
url: "modules/OutShop/getReservations.php",
data: {item_id: $("#item-id").val()},
async: false,
success: function (dates) {
resDates = dates;
//done = true;
}
});
}
$("#item-datepicker-min").datepicker({
showButtonPanel: true,
defaultDate: +3,
minDate: +3,
beforeShowDay: markDate,
onSelect: function(selectedDate) {
$("#item-datepicker-max").datepicker("option", "minDate", selectedDate);
}
});
$("#item-datepicker-max").datepicker({
showButtonPanel: true,
minDate: +3,
defaultDate: +6,
beforeShowDay: markDate,
onSelect: function(selectedDate) {
$("#item-datepicker-min").datepicker("option", "maxDate", selectedDate);
}
});
});
EDIT
For further information: This is an example json object I got from the ajax response.
[{"status":3,"day":"2013-04-10"},{"status":3,"day":"2013-04-11"},{"status":3,"day":"2013-04-12"},{"status":3,"day":"2013-04-13"},{"status":2,"day":"2013-04-10"},{"status":2,"day":"2013-04-11"},{"status":2,"day":"2013-04-12"},{"status":2,"day":"2013-04-13"}]
Looks like your months are offset by 1, the javascript method date.getMonth() returns the months zero-based (eg. January is 0, Feb is 1) and your PHP script returns the date in normal format (Jan is 1, Feb is 2)
Check this
So if you change
var d = (date.getFullYear() + "-" + ("0" + date.getMonth()).slice(-2) + "-" + ("0" + date.getDate()).slice(-2));
to
var d = (date.getFullYear() + "-" + ("0" + date.getMonth()+1).slice(-2) + "-" + ("0" + date.getDate()).slice(-2));
you should get the right month showing
I apologise if this is a really basic question but I am using the following jquery plugin:
http://jonathanleighton.com/projects/date-input
I want to change the date from YYYY-MM-DD to DD/MM/YYYY using his suggestion under customisations. I tried to do the following which I thought would work but it completely breaks it:
$.extend(DateInput.DEFAULT_OPTS, {
stringToDate: function(string) {
var matches;
if (matches = string.match(/^(\d{4,4})-(\d{2,2})-(\d{2,2})$/)) {
return new Date(matches[1], matches[2] - 1, matches[3]);
} else {
return null;
};
},
dateToString: function(date) {
var month = (date.getMonth() + 1).toString();
var dom = date.getDate().toString();
if (month.length == 1) month = "0" + month;
if (dom.length == 1) dom = "0" + dom;
return date.dom + "/" + month + "/" + getFullYear();
}
});
It's the following line where it all goes wrong:
return date.dom + "/" + month + "/" + getFullYear();
Could anyone offer a suggestion as to what I'm doing wrong?
You should try using the jQuery UI datepicker. Very easy to format the date
http://jqueryui.com/demos/datepicker/
i don't think you need the "date" in date.dom:
try replacing this:
return date.dom + "/" + month + "/" + getFullYear();
with this:
return dom + "/" + month + "/" + getFullYear();