jQuery datetimepicker: disable time - jquery-ui

I am using the XDSoft jQuery datetimepicker in my app (Ruby on Rails 4 (just for information, not using bootstrap datetimepicker)).
I was wondering if there is a way to disable/deactivate a specific time at a specific date, for example disable only 17:00 on 12/17/2014?
disabledDates: ['...'] disables a specific date.
I tried disabledDateTimes and disabledTimes but they don't work.
Thanks.

Here is one example of how this can be done using the XDSoft DateTimePicker you are asking about.
I have a specificDates array which you can use to add dates you want to target.
I also have an hoursToTakeAway multi dimensional array which corresponds with the specificDates array where you can specify the hours to take away.
HTML
<input class="eventStartDate newEventStart eventEditDate startTime eventEditMetaEntry" id="from_date" name="from_date" placeholder="Start date and time" readonly="readonly" type="text" />
Javascript
var specificDates = ['24/12/2014','17/12/2014'];
var hoursToTakeAway = [[14,15],[17]];
$('#from_date').datetimepicker({
format:'d.m.Y H:i',
timepicker: true,
lang: 'en',
onGenerate:function(ct,$i){
var ind = specificDates.indexOf(ct.dateFormat('d/m/Y'));
$('.xdsoft_time_variant .xdsoft_time').show();
if(ind !== -1) {
$('.xdsoft_time_variant .xdsoft_time').each(function(index){
if(hoursToTakeAway[ind].indexOf(parseInt($(this).text())) !== -1) {
$(this).hide();
}
});
}
}
});
Example
Fiddle
Basically I am taking advantage of the onGenerate event which happens after each calendar has been rendered. Then I am checking to see if the date matches the specified day and if it does, we iterate through all the time elements and hide the ones specified for the specific date.
Updated Fiddle implementing disable.
Fiddle 2

This code is working for me:
var specificDates = ['24/12/2014','17/12/2014'];
var hoursToTakeAway = [[14,15],[17]];
$('#from_date').datetimepicker({
format:'d.m.Y H:i',
timepicker: true,
lang: 'en',
onGenerate:function(ct,$i){
var ind = specificDates.indexOf(ct.dateFormat('d/m/Y'));
$('.xdsoft_time_variant .xdsoft_time').show();
if(ind !== -1) {
$('.xdsoft_time_variant .xdsoft_time').each(function(index){
if(hoursToTakeAway[ind].indexOf(parseInt($(this).text())) !== -1) {
$(this).hide();
}
});
}
}
});

If someone still need solution, i write code to disable ranges of time in jquery-ui-datepicker.
First I need to init ranges, that will be disabled at current date:
dateObj1 = new Date(2016,6,22,0);
dateObj2 = new Date(2016,6,27,10);
diap1 = [dateObj1, dateObj2];
dateObj1 = new Date(2016,6,27,13);
dateObj2 = new Date(2016,6,27,14);
diap2 = [dateObj1, dateObj2];
dateObj1 = new Date(2016,6,27,20);
dateObj2 = new Date(2016,6,29,10);
diap3 = [dateObj1, dateObj2];
dateObj1 = new Date(2016,6,27,0);
dateObj2 = new Date(2016,6,27,13);
diap4 = [dateObj1, dateObj2];
dateObj1 = new Date(2016,7,02,4);
dateObj2 = new Date(2016,7,02,4,59);
diap5 = [dateObj1, dateObj2];
diapazons = [diap1,diap2,diap3,diap4,diap5];
Then I need function, to proceed this ranges, detect intersections and create ranges, that will be displayed:
function getAvailableTimes(restricts, curr_year, curr_month, cur_day)
{
day_diaps = [[new Date(curr_year,curr_month,cur_day,0), new Date(curr_year,curr_month,cur_day,23,59,59)]];
restricts.forEach(function(item, i, arr) {
day_diaps.forEach(function(day_diap, i_d, arr_d) {
//console.log('day = '+day_diap.toString());
if (day_diap[0] >= item[1])
{
//console.log(i+' раньше');
}
else if (day_diap[1] <= item[0])
{
//console.log(i+' позже');
}
else if (day_diap[0] >= item[0] && day_diap[1] <= item[1])
{
//console.log(i+' закрыт полностью');
arr_d.splice(i_d,1);
}
else if (day_diap[0] >= item[0] && day_diap[1] >= item[1])
{
day_diap[0] = item[1];
//console.log(i+' ранее перекрытие, начало смещено на '+ day_diap.toString());
}
else if (day_diap[0] <= item[0] && day_diap[1] <= item[1])
{
day_diap[1] = item[0];
//console.log(i+' позднее перекрытие, конец смещен на '+ day_diap.toString());
}
else if (day_diap[0] <= item[0] && day_diap[1] >= item[1])
{
new_diap = [item[1],day_diap[1]];
arr_d.push(new_diap);
day_diap[1] = item[0];
//console.log(i+' restrict полностью умещается в диапазон '+ day_diap.toString());
//console.log(i+' добавлен диапазон '+ new_diap.toString());
}
});
});
return day_diaps;
}
And code in of datetimepicker:
<input type="text" id="default_datetimepicker"/>
<script>
$.datetimepicker.setLocale('ru');
var dates_to_disable = ['30-07-2016','31-07-2016','04-08-2016'];
$('#default_datetimepicker').datetimepicker({
formatTime:'H:i',
lang: "ru",
defaultTime:"10:00",
formatDate:'d-m-Y',
todayButton: "true",
minDate:'01-01--1970', // yesterday is minimum date
disabledDates:dates_to_disable,
onGenerate:function(ct,i){
var dates = jQuery(this).find('.xdsoft_date ');
$.each(dates, function(index, value){
year = jQuery(value).attr('data-year');
month = jQuery(value).attr('data-month');
date = jQuery(value).attr('data-date');
diaps = getAvailableTimes(diapazons,year,month,date);
net_nihrena = true;
diaps.forEach(function(day_diap, i_d, arr_d) {
net_nihrena = false;
});
if (net_nihrena)
{
jQuery(value).addClass('xdsoft_disabled');
//jQuery(value).addClass('xdsoft_restricted');
}
});
cur_date = ct;
diaps = getAvailableTimes(diapazons,ct.getFullYear(),ct.getMonth(),ct.getDate());
var times = jQuery(this).find('.xdsoft_time ');
$.each(times, function(index){
var hour = $(this).attr('data-hour');
var minute = $(this).attr('data-minute');
cur_date.setHours(hour,minute,0);
net_takogo_vremeni = true;
diaps.forEach(function(day_diap, i_d, arr_d) {
if ((day_diap[0] < cur_date && day_diap[1] > cur_date) || hour==0)
{
net_takogo_vremeni = false;
}
});
if (net_takogo_vremeni)
{
$(this).addClass('xdsoft_disabled');
//$(this).addClass('xdsoft_restricted');
}
});
},
onSelectDate : function(ct) {
}
});
</script>

Related

Images gets truncated after setting SRC Value (iOS)

I ran into a strange limitation from iOS/Safari/Chrome.
The user can select an image and it filecontent gets pasted into a input element.
The Length of the both are unequal. Is this an iOS limitation?
L.users.importConfigurations = function(options) {
var target = null;
this._getInputFileElement = function() {
var that = this;
fileInput = $('<input type="file" accept="image/*" style="display:none;" capture="camera" />');
fileInput.change(function() {
that._handleFiles(fileInput);
});
return fileInput;
};
this.showFileSelectionDialog = function() {
var fileInput = this._getInputFileElement();
fileInput.click();
};
this._handleFiles = function(fileInput) {
var files = fileInput[0].files;
if (files && files.length) this._readFile(files[0]);
};
this._readFile = function(fileInfo) {
var that = this;
var reader = new FileReader();
reader.onload = function(e) {
that._uploadFile(e.target.result);
};
reader.readAsDataURL(fileInfo);
};
this._uploadFile = function(fileData) {
var fbValue = $(options.target).closest('.fileboxframe').find(".fileboxvalue");
if (fbValue && fbValue.length > 0) {
alert("Length before: " + fileData.length.toString());
fbValue.attr('src', fileData);
alert("Length after (Should be same): " + fileData.length.toString());
alert("Length after (Should be same): " + fbValue.attr("src").length.toString());
}
};
this.showFileSelectionDialog();
};
https://jsfiddle.net/ChristophWeigert/81qu41L5/
I found an answer in this topic:
Why is the default max length for an input 524288?
Solution was to use a textare and not a textbox.

jquery: focus jumps before event runs

The focus moves to the next input field before the event is fired. Can anyone help me find the bug, or figure out how to find it myself?
The goal is to catch the keyup event, verify that it is tab or shift+tab, and then tab as though it were tabbing through a table. When the focus gets to the last input that is visible, the three rows (see fiddle for visual) should move together to reveal hidden inputs. Once to the end of the inputs in that row, the three rows will slide back down to the beginning again, kind of like a carriage return on a typewriter, or tabbing into a different row in a table.
Right now, the tab event is moving just the row that holds the focus, and it is moving it before my script even starts to run. I just need to know why this is happening so that I can research how to resolve it.
Any help you can offer is appreciated. Please let me know if you need more information.
P.S. Using jquery 1.9.1
Link to Fiddle
jQuery(document).ready(function ($) {
// bind listeners to time input fields
//$('.timeBlock').blur(validateHrs);
$('.timeBlock').keyup(function () {
var caller = $(this);
var obj = new LayoutObj(caller);
if (event.keyCode === 9) {
if (event.shiftKey) {
obj.dir = 'prev';
}
obj.navDates();
}
});
// bind listeners to prev/next buttons
$('.previous, .next').on('click', function () {
var str = $(this).attr('class');
var caller = $(this);
var obj = new LayoutObj(caller);
obj.src = 'pg';
if (str === 'previous') {
obj.dir = 'prev';
}
obj.navDates();
});
});
function LayoutObj(input) {
var today = new Date();
var thisMonth = today.getMonth();
var thisDate = today.getDate();
var dateStr = '';
var fullDates = $('.dateNum');
var splitDates = new Array();
this.currIndex = 0; //currIndex defaults to 0
this.todayIndex;
fullDates.each(function (index) {
splitDates[index] = $(this).text().split('/');
});
//traverse the list of dates in the pay period, compare values and stop when/if you find today
for (var i = 0; i < splitDates.length; i++) {
if (thisMonth === (parseInt(splitDates[i][0], 10) - 1) && thisDate === parseInt(splitDates[i][1], 10)) {
thisMonth += 1;
thisMonth += '';
thisDate += '';
if (thisMonth.length < 2) {
dateStr = "0" + thisMonth + "/";
}
else {
dateStr = thisMonth + "/";
}
if (thisDate.length < 2) {
dateStr += "0" + thisDate;
}
else {
dateStr += thisDate;
}
fullDates[i].parentNode.setAttribute('class', 'date today');
this.todayIndex = i;
break;
}
}
//grab all of the lists & the inputs
this.window = $('div.timeViewList');
this.allLists = $('.timeViewList ul');
this.inputs = $('.timeBlock');
//if input`isn't null, set currIndex to match index of caller
if (input !== null) {
this.currIndex = this.inputs.index(input);
}
//else if today is in the pay period, set currIndex to todayIndex
else if (this.todayIndex !== undefined) {
this.currIndex = this.todayIndex;
}
//(else default = 0)
//grab the offsets for the cell, parent, and lists.
this.winOffset = this.window.offset().left;
this.cellOffset = this.inputs.eq(this.currIndex).offset().left;
this.listOffset = this.inputs.offset().left;
//grab the width of a cell, the parent, and lists
this.cellWidth = this.inputs.outerWidth();
this.listWidth = this.inputs.last().offset().left + this.cellWidth - this.inputs.eq(0).offset().left;
this.winWidth = this.window.outerWidth();
//calculate the maximum (left) offset between the lists and the parents
this.offsetMax = (this.listWidth - this.winWidth);
//set default scroll direction as fwd, and default nav as tab
this.dir = 'next';
this.src = 'tab';
//grab the offsets for the cell, parent, and lists.
this.cellOffset = this.inputs.eq(this.currIndex).offset().left;
this.listOffset = this.inputs.eq(0).offset().left;
this.winOffset = this.allLists.parent().offset().left;
//calculate the maximum (left) offset between the lists and the parents
this.offsetMax = (this.listWidth - this.winWidth);
}
LayoutObj.prototype.focusDate = function () {
this.inputs.eq(this.currIndex).focus();
};
LayoutObj.prototype.slideLists = function (num) {
this.listOffset += num;
this.allLists.offset({ left: this.listOffset });
};
LayoutObj.prototype.navDates = function () {
if (!this.inWindow()) {
var slide = 0;
switch (this.src) {
case 'pg':
slide = this.winWidth - this.cellWidth;
break;
case 'tab':
slide = this.cellWidth + 1;
break;
default:
break;
}
if (this.dir === 'next') {
slide = -slide;
}
this.slideLists(slide);
}
this.focusDate();
};
LayoutObj.prototype.inWindow = function () {
//detects if cell intended for focus is visible in the parent div
if ((this.cellOffset > this.winOffset) && ((this.cellOffset + this.cellWidth) < (this.winOffset + this.winWidth))) {
return true;
}
else {
return false;
}
}
All it needed was 'keydown()' instead of 'keyup().'

Twitter integration stopped working recently

This was the code, I was using but it has stopped working. Get anyone help me to solve this as I dont have much knowledge about this.
// JQuery Twitter Feed. Coded by www.tom-elliott.net (2012) and modified from https://twitter.com/javascripts/blogger.js
var p = jQuery.noConflict();
p(document).ready(function () {
var twitterprofile = "waateanews";
var hidereplies = true;
var showretweets = true;
var showtweetlinks = true;
var displayLimit = 3;
p.getJSON('https://api.twitter.com/1/statuses/user_timeline/'+twitterprofile+'.json?include_rts='+showretweets+'&exclude_replies='+hidereplies+'&count=30&callback=?',
function(feeds) {
var feedHTML = '';
var displayCounter = 1;
for (var i=0; i<feeds.length; i++) {
var username = feeds[i].user.screen_name;
var profileimage = feeds[i].user.profile_image_url_https;
var status = feeds[i].text;
if ((feeds[i].text.length > 1) && (displayCounter <= displayLimit)) {
if (showtweetlinks == true) {
status = addlinks(status);
}
if (displayCounter == 1) {
//feedHTML += '<h1>#'+twitterprofile+' on Twitter</h1>';
}
feedHTML += '<div class="twitter-article">';
feedHTML += '<div class="twitter-pic"><img src="'+profileimage+'"images/twitter-feed-icon.png" width="42" height="42" alt="twitter icon" /></div>';
feedHTML += '<div class="twitter-text"><p>'+status+'<br/><span class="tweet-time">'+relative_time(feeds[i].created_at)+'</span></p></div>';
feedHTML += '</div>';
displayCounter++;
}
}
p('#twitter-feed').html(feedHTML);
});
function addlinks(data) {
//Add link to all http:// links within tweets
data = data.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
return ''+url+'';
});
//Add link to #usernames used within tweets
data = data.replace(/\B#([_a-z0-9]+)/ig, function(reply) {
return ''+reply.charAt(0)+reply.substring(1)+'';
});
return data;
}
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
if (delta < 60) {
return 'less than a minute ago';
} else if(delta < 120) {
return 'about a minute ago';
} else if(delta < (60*60)) {
return (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (120*60)) {
return 'about an hour ago';
} else if(delta < (24*60*60)) {
return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
return '1 day ago';
} else {
return (parseInt(delta / 86400)).toString() + ' days ago';
}
}
});
</script>
<div id="twitter-feed"></div>
<div id="twitter_footer">Follow us on twitter</div>
Twitter has retired the API v1. Details here. You will have to rewrite the code to use oAuth or use some ready made scripts. I will let you figure that out.

Enable first sunday in Jquery UI datapicker

I'm currently working on a Jquery datepicker where holidays are disabled and all sundays, except for the first one in each month. I have been trying to play around a little with the code, and found out how to disable all sundays and holidays, but i cant figure out how to enable the first sunday of evey month.
Currently my code looks like this:
<script type="text/javascript">
(function(){
var natDays = [[12, 24],[12, 25], [1,1], [12, 31]];
var daysToDisable = [0];
function nationalDays(date) {
for (i = 0; i < natDays.length; i++) {
if (date.getMonth() == natDays[i][0] - 1
&& date.getDate() == natDays[i][1]) {
return [false, natDays[i][2] + '_day'];
}
}
for (i = 0; i < daysToDisable.length; i++) {
if ($.inArray(day, daysToDisable) != -1) {
return [false];
}
}
return [true];
}
// Datepicker
$('#datepicker').datepicker({
inline: true,
firstDay: 1,
changeYear: true,
changeMonth: true,
beforeShowDay: nationalDays,
});
});
</script>
Logically, the first Sunday of the month is always on or before the 7th and the second (and subsequent) Sundays are after the 7th.
function nationalDays(date) {
for (i = 0; i < natDays.length; i++) {
if (date.getMonth() == natDays[i][0] - 1 && date.getDate() == natDays[i][1]) {
return [false, natDays[i][2] + '_day'];
}
}
if (date.getDate() > 7 && $.inArray(date.getDay(), daysToDisable) != -1)
return [false];
}
return [true];
}
I would also suggest to change the structure of your natDays array to a flat array in order to speed up lookups. For your class prefixes (which are not set in your example), you can use an extra array with matching indices. Your final function would look like this:
var natDays = ["12-24", "12-25", "1-1", "12-31"];
var classPrefixes = ["", "", "", ""];
var daysToDisable = [0];
function nationalDays(date) {
var index = $.inArray((date.getMonth() + 1) + "-" + date.getDate(), natDays);
if (index != -1) {
return [false, classPrefixes[index] + '_day'];
}
if (date.getDate() > 7 && $.inArray(date.getDay(), daysToDisable) != -1)
return [false];
}
return [true];
}
The method you're looking for is date.getDay(), which will return a number from 0 to 6, with 0 being Sunday.
function nationalDays(date) {
if(date.getDay() == 0) {
// do stuff...

Timeout XMLHttpRequest

How can I add a timeout to the following script? I want it to display text as "Timed Out".
var bustcachevar = 1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects = ""
var rootdomain = "http://" + window.location.hostname
var bustcacheparameter = ""
function ajaxpage(url, containerid) {
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject) { // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
} catch (e) {
try {
page_request = new ActiveXObject("Microsoft.XMLHTTP")
} catch (e) {}
}
} else
return false
document.getElementById(containerid).innerHTML = '<img src="load.gif" border="0"><br><br><strong>Generating Link...</strong>'
page_request.onreadystatechange = function () {
loadpage(page_request, containerid)
}
if (bustcachevar) //if bust caching of external page
bustcacheparameter = (url.indexOf("?") != -1) ? "&" + new Date().getTime() : "?" + new Date().getTime()
page_request.open('GET', url + bustcacheparameter, true)
page_request.send(null)
}
function loadpage(page_request, containerid) {
if (page_request.readyState == 4 && (page_request.status == 200 || window.location.href.indexOf("http") == -1))
document.getElementById(containerid).innerHTML = page_request.responseText
else if (page_request.readyState == 4 && (page_request.status == 404 || window.location.href.indexOf("http") == -1))
document.getElementById(containerid).innerHTML = '<strong>Unable to load link</strong><br>Please try again in a few moments'
}
using the timeout properties of XMLHttpRequest object for example.
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
alert("ready state = 4");
}
};
xhr.open("POST", "http://www.service.org/myService.svc/Method", true);
xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
xhr.timeout = 4000; // Set timeout to 4 seconds (4000 milliseconds)
xhr.ontimeout = function () { alert("Timed out!!!"); }
xhr.send(json);
the above code works for me!
Cheers

Resources