Assign a JS function to a Dynamic ID for Bootstrap-Datepicker - javascript

I need to only show month and year when a user selects the datepicker. I have followed examples and tried to find a problem but it just seems to not be working. Can some one please help?
cshtml file
<div class=" accordion" id="accordion">
<i class="icon-plus-sign app-icon-orange icon-2x" style="cursor:pointer" id="btnAddTierGroup"></i> Add new date range
#*Create a panel for each time period*#
#for (var i = 0; i < Model.Periods.Count; i++)
{ #Html.EditorFor(x => x.Periods[i], "TimePeriodTiers") }
</div>
JS (minViewMode: 1 is months for those unfamiliar with bootstrap)
$(document).ready(function () {
$('[id^="Periods"]').datepicker({
format: "mm/dd/yyyy",
minViewMode: 1
});
})
EDIT:
I found I had two problems. One fixed and one still exists.
1. the selector id^="Periods" was attaching to too many objects. Fixed by using 'id$=BeginDate' so it only grabs what I need it to.
2. there is a function in the JS that stop the user from selecting past the end date of other Tiers. the two scenarios are as follows:
the function works but allows user to pick back dates
<script type="text/javascript">
var MaxTierCount = 25;
var MaxRate = #ViewBag.RateNotification
SetUpTableSorter();
$('[id$=BeginDate]').ready(function () {
$('[id$=BeginDate]').datepicker({
format: "mm/dd/yyyy",
startView: "months",
minViewMode: 1
});
})
setupDateRanges($('#accordion'));
Scenario 2: user is unable to pick back dates but the function does not work:
<script type="text/javascript">
var MaxTierCount = 25;
var MaxRate = #ViewBag.RateNotification
SetUpTableSorter();
setupDateRanges($('#accordion'));
$('[id$=BeginDate]').ready(function () {
$('[id$=BeginDate]').datepicker({
format: "mm/dd/yyyy",
startView: "months",
minViewMode: 1
});
})
Any help?

Related

Gray out all but certain dates on Bootstrap datepicker

I'm setting up a datepicker, but I only want the user to be able to select dates from a pre-determined date array I have populated. These are dates where relevant events happened. Nothing happened on the other dates outside of the array.
Below is an example array that I would have.
dateArr = ["2015-10-27", "2015-10-29", "2015-11-10", "2016-11-30", "2016-12-07", "2017-06-29", "2017-06-30", "2017-10-23", "2017-12-13", "2018-03-27", "2018-03-29", "2018-03-30", "2018-03-31", "2018-04-02", "2018-04-07", "2018-04-08", "2018-04-09"]
I've looked at other examples, but none seem to do what I'm trying to do. The array dates would be selectable, and the rest would be grayed out.
Try with below Jquery code:
HTML Code:
<div id="datepicker"></div>
Jquery Code :
jQuery(function(){
var enableDays = ["7-8-2019", "13-8-2019"];
function enableAllTheseDays(date) {
var sdate = $.datepicker.formatDate( 'd-m-yy', date)
console.log(sdate)
if($.inArray(sdate, enableDays) != -1) {
return [true];
}
return [false];
}
$('#datepicker').datepicker({dateFormat: 'dd-mm-yy', beforeShowDay: enableAllTheseDays});
});
JFiddle Code Here:
http://jsfiddle.net/qampw1n5/

jQuery DatePicker restrict dates

I am trying to restrict jquery datepicker values. So the the from date can not exceed the to date and vice versa.
Demo https://jsfiddle.net/DTcHh/21594/
I've tried multiple instances of this but can not seem to get it to work. Is it because I am using the UK date format?
$(".datepicker").datepicker({
dateFormat: 'dd-mm-yy'
});
$('#from_date').datepicker({
onSelect: function(dateStr) {
var min = $(this).datepicker('getDate') || new Date(); // Selected date or today if none
var max = new Date(min.getTime());
max.setMonth(max.getDay() + 1); // Add one month
$('#to_date').datepicker('option', {minDate: min, maxDate: max});
}
});
$('#to_date').datepicker({
onSelect: function(dateStr) {
var max = $(this).datepicker('getDate'); // Selected date or null if none
$('#from_date').datepicker('option', {maxDate: max});
}
});
As i'm new to JavaScript i'm keen to know exactly why my code doesn't work, so i can learn from this.
You cannot initialize date picker on same element twice. First, you called the date picker on element with its class; then with its ID.
Try to move the date format to date picker default function.
$.datepicker.setDefaults({
dateFormat: 'dd-mm-yy'
});
Or, you need to set dateFormat every time you initialize a date picker element.

Jquery Datetimepicker disable dates

i am using jquery datetime picker for getting date and time using
$(document).ready(function() {
$('#pickup_date').datetimepicker({
controlType: 'select',
timeFormat: 'hh:mm tt'
});
but i need to enable 3 weeks from the current date only.How to solve this.thanks in advance
<script>
function DisableWeekDays(date) {
var weekenddate = $.datepicker.noWeekends(date);
// In order to disable weekdays, we will invert the value returned by noWeekends functions.
// noWeekends return an array with the first element being true/false.. So we will invert the first element
var disableweek = [!weekenddate[0]];
return disableweek;
}
$(function() {
$( "#datepicker" ).datetimepicker({
beforeShowDay: DisableWeekDays
});
});
</script>
$('yourSelectorForDateTimePicker').datetimepicker({
formatDate:'Y/m/d',
minDate:0, //Today You can also '+1970/01/21' or '-1970/01/21' both ended up meaning -0 or +0
maxDate:'+1970/01/21' //3*7 days from today.
});
use minDate and maxDate
0 means 1970/01/01 which is start time of Unix time.You can plus/minus the String Date to set range of selectable dates.
The case You want to set the range to be yesterday to tomorrow it'll be
$('yourSelectorForDateTimePicker').datetimepicker({
formatDate:'Y/m/d',
minDate:'-1970/01/02', //Yesterday(plus one day from the 0 '1970/01/01')
maxDate:'+1970/01/02' //Tomorrow(minus one day from the 0 '1970/01/01')
});
http://xdsoft.net/jqplugins/datetimepicker/
The above answer is a good one, but if you want to set the date dynamically (based on the current date).
$(function () {
var currentDate = new Date();
var date = currentDate.toDateString();
$("#datetimepicker1").val(new Date() + " 00:01:00");
$('#datetimepicker1').datetimepicker({
format: 'DD/MM/YYYY',
minDate: date
});
});
Get the current date into a variable
Convert the date to a string
Pass the string to minDate
Or
$(function () {
$("#datetimepicker1").val(new Date() + " 00:01:00");
$('#datetimepicker1').datetimepicker({
format: 'DD/MM/YYYY',
minDate: moment()
});
});
Using JSMoment and pass moment.

Jquery Date picker is Selecting today and default date given

I am using Jquery date picker for selecting a date, and I'd like to be able to default the selection to a given date.
Here's my code:
var SelectDate=new Date(2013, 06,25 , 0, 0, 0, 0) ;
$("#OnwardTravelDate").datepicker({
numberOfMonths: 2,
dateFormat: 'dd/mm/yy',
minDate: datePickMinDate_DT,
maxDate: datePickMaxDate_DT,
defaultDate: SelectDate
});
But the date selector control highlights both today's date and the date 'selectDate' . I want only 'selectDate' as highlighted
removeClass("ui-state-highlight"); should fix your problem.
but if you just want the highlight of today never show again, you may get the datepicker's source (jquery.ui.datepicker.js) and find this line to remove:
(printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') +
then compile it to use.
Datepicker assigns different classes to "today" and "selected day":
today - ui-state-highlight
selected day - ui-state-active
You can either remove or override styling of ".ui-datepicker .ui-state-highlight" or remove the class:
$("#OnwardTravelDate a.ui-state-highlight").removeClass("ui-state-highlight");
What about setting the value of #OnwardTravelDate in html or jquery?
HTML:
<input type="text" id="OnwardTravelDate" value="25/06/2013" />
jQuery:
$("#OnwardTravelDate").val("25/06/2013"); // Before datepicker code
Then you don't need your defaultDate: SelectDate at all :)
Hope that helps.
Edit: (more info)
You could also try the setDate method:
$("#OnwardTravelDate").datepicker("setDate", SelectDate); // After datepicker code
Edit: jsfidle
This JS fidle seems to work for me: jsfiddle
Maybe the styling on your theme makes it look like it's selected?
EDIT1: From here I found just a fix, but I'm not able to handle with your code.
$( "#datepicker" ).datepicker({
beforeShow: function(input, inst) {
window.setTimeout(function(){
$(inst.dpDiv).find('.ui-state-highlight.ui-state-hover').removeClass('ui-state-highlight ui-state-hover')
},0)
},
});
Check this JSFiddle and if possible update it with your code you trying.
EDIT2: By overriding the default css .ui-datepicker-today and a.ui-state-highlight of with the below one.
.ui-datepicker-today a.ui-state-highlight {
border-color: #d3d3d3;
background: #e6e6e6 url(/themeroller/images/ui-bg_glass_75_e6e6e6_1x400.png) 50% 50% repeat-x;
color: #555555;
}
Check out this JSFiddle

Enable Datepicker only when first field has a value

Right now, the End Date selection is disabled. I want to only enable this when a Start Date is selected.
if( $('#datepicker1').val().length === 0) {
$('#datepicker2').datepicker("disable");
} else {
$('#datepicker2').datepicker("enable");
}
This clearly does not work. If I insert value = 'random date' into my first input field, it works fine. I'm not too sure on how do this. Clearly not as easy as I had hoped.
My other problem, or hope, is to disable the dates including and before the first selection.
You know, pick Start Date, and every date before and said date for the next picker would be disabled. But that is a whole other problem.
You can use something like this:
var end = $('#end').datepicker();
// Defining a function, because we're binding this to two different events
function enableEnd() {
end.attr('disabled', !this.value.length) // Enable the end input element if the first one has anything in it
.datepicker('option', 'minDate', this.value); // Set the minimum date to the date in the first input
}
$('#start').datepicker({
onSelect: enableEnd // Call enableEnd when a date is selected in the first datepicker
}).bind('input', enableEnd); // Do the same when something is inputted by the user
It's not really a good idea to enable the datepicker in the second field only after the first has been filled in, because the user can still add things into the second field manually, and you lose the format validation usually offered by jQuery UI datepicker. Instead, we disable the second input element directly.
See it working here: http://www.jsfiddle.net/yijiang/KwhLw/
Also note that we're using the input event here, because although it has less broad compatibility, is better than the usual methods used for keyboard event capturing. See a full discussion on this here: http://whattheheadsaid.com/tag/oninput
Just try this approach -
$('#datepicker1').datepicker({
//your other configurations.
onSelect: function(){
//enable datepicker 2 over here.
}
});
I would use the getDate method and see if it's null (nothing selected/entered), like this:
if($('#datepicker1').datepicker("getDate") === null)
For the other issue, check out the date range demo for the datepicker, it has a start/end date like you're aiming for.
Well, question is answered. For those who want to know what I have, here it is.
To change a Start Date and an End Date (A date range if you will) into an array of individual dates, I used this:
function createDateRangeArray($strDateFrom,$strDateTo) //Changes a Range of Dates to Specific Dates
{
static $aryRange = array(); //Creates an Array
$iDateFrom = mktime(1,0,0,substr($strDateFrom,5,2), substr($strDateFrom,8,2),substr($strDateFrom,0,4));
$iDateTo = mktime(1,0,0,substr($strDateTo,5,2), substr($strDateTo,8,2),substr($strDateTo,0,4));
if ($iDateTo >= $iDateFrom)
{
array_push($aryRange,date('Y-m-d',$iDateFrom)); // first entry
while ($iDateFrom<$iDateTo)
{
$iDateFrom += 86400; // add 24 hours
array_push($aryRange,date('Y-m-d',$iDateFrom));
}
}
return $aryRange; //Returns to step 1 and adds another value into the array
}
To get every date from my SQL Database and push them into a single array, this was used:
$query = "SELECT startdate, enddate FROM classdetails";
$results = mysql_query($query);
while ($arrays = mysql_fetch_array($results))
{
$aryDates = createDateRangeArray($arrays['startdate'],$arrays['enddate']);
echo "<br />";
}
So now I have managed to get every date range from an entire list of classes and made one huge array.
Now I had to use this array to actually disable the dates. Using the functions of which Yi Jiang has no generously wrote (thank you to everyone who helped me), the next step is:
$(function()
{
//To enable End Date picker only when Start Date has been chosen (And to disable all dates prior of said date)
var end = $('#enddate').datepicker( {numberOfMonths: 3, beforeShowDay: checkAvailability,});
// Defining a function, because we're binding this to two different events
function enableEnd() {
end.attr('disabled', !this.value.length) // Enable the end input element if the first one has anything in it
.datepicker('option', 'minDate', this.value); // Set the minimum date to the date in the first input
}
//End of function
// Datepicker
$('#startdate').datepicker({
numberOfMonths: 3,
beforeShowDay: checkAvailability,
onSelect: enableEnd // Call enableEnd when a date is selected in the first datepicker
}).bind('input', enableEnd); // Do the same when something is inputted by the user
//hover states on the static widgets
$('#dialog_link, ul#icons li').hover(
function() {$(this).toggleClass('ui-state-hover');}
);
});
//End of Function
//Disabling all dates where selected room and speaker is unavailable
var $myBadDates = new Array (<?php foreach($aryDates as $disabledate) { echo " \"$disabledate\","; } echo " 1"; ?>); //Creates the array (The echo " 1"; is merely to close the array and will not affect the outcome
function checkAvailability(mydate){
var $return=true;
var $returnclass ="available";
$checkdate = $.datepicker.formatDate('yy-mm-dd', mydate);
for(var i = 0; i < $myBadDates.length; i++)
{
if($myBadDates[i] == $checkdate)
{
$return = false;
$returnclass= "unavailable";
}
}
return [$return,$returnclass];
}
//End of function
The only thing in my body right now, for testing purposes, are:
<!-- Datepicker -->
<h2 class="header">Datepicker</h2>
<span>
Start Date: <input type="text" id="startdate" />
</span>
<span>
End Date: <input type="text" id="enddate" disabled="disabled" />
</span>
It's long, yes, but it works. Thank you to everyone who helped me get this working.
The edit was me changing a function to a JQuery function that exists (of which for some reason I did not use in the first place); toggleClass. Thanks for picking that out.

Categories