I have 2 datepickers - date from and date to, something like hotel reservation system. How do I check (and show hidden div.error) if there are some disabled days in selected period?
Ex. - selected dates - from 2021-12-20 to 2021-12-31; disabled days are ["2021-12-25", "2021-12-26"] -> show "error".
<div class="error" style="display:none">Sorry, but we have no available rooms in selected dates.</div>
<script>
$( function() {
var disableddates = ["2021-12-25", "2021-12-26"];
$.datepicker.setDefaults($.datepicker.regional["de"]);
$( "#from" ).datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate("yy-mm-dd", date);
return [ disableddates.indexOf(string) == -1 ]
}
});
$( "#to" ).datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate("yy-mm-dd", date);
return [disableddates.indexOf(string) == -1 ]
}
});
});
</script>
Related
I'm trying to change the value of a jQuery datepicker input element in a form to the first date in the week of the user-selected date once the submit button is clicked but before the form is actually submitted.
I'm finding that the following Javascript works (using a class selector in .find()):
$("form").submit( function(event) {
$(this).closest('form').find('.week-picker').datepicker( "setDate", startDate );
var current_date = $(this).closest('form').find('.week-picker').datepicker( "getDate" );
return;
});
startDate is a Date object.
But this code does not work (using an ID selector in .find()):
$("form").submit( function(event) {
$(this).closest('form').find("#week-picker").datepicker( "setDate", startDate );
var current_date = $(this).closest('form').find('.week-picker').datepicker( "getDate" );
return;
});
console.log($(this).closest('form').find(".week-picker").datepicker( "setDate", startDate ).val()); produces a proper date, like 06/27/2018.
console.log($(this).closest( 'form' ).find('#week-picker').val()); produces undefined.
Why is this happening? Isn't an ID a valid selector?
HTML:
<form action="/checkin" method="post">
<div class="form-group row mb-2">
<div class="col-md-6 offset-md-3">
<input class="week-picker form-control" type="text" id="week-picker" name="week_start" placeholder="Select week" style="opacity: 0;position: absolute;">
</div>
</div>
<div class="form-group row mt-4">
<div class="col">
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
</div>
</div>
</form>
The datepicker portion of my JS:
var startDate;
var endDate;
var selectCurrentWeek = function() {
window.setTimeout(function () {
$('.week-picker').find('.ui-datepicker-current-day a').addClass('ui-state-active')
}, 1);
}
$('.week-picker').datepicker( {
showOtherMonths: true,
selectOtherMonths: true,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate');
startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
var dateFormat = inst.settings.dateFormat || $.datepicker._defaults.dateFormat;
$(this).closest( 'form' ).find('#startDate').text($.datepicker.formatDate( dateFormat, startDate, inst.settings ));
$(this).closest( 'form' ).find('#endDate').text($.datepicker.formatDate( dateFormat, endDate, inst.settings ));
selectCurrentWeek();
},
beforeShowDay: function(date) {
var cssClass = '';
if(date >= startDate && date <= endDate)
cssClass = 'ui-datepicker-current-day';
return [true, cssClass];
},
onChangeMonthYear: function(year, month, inst) {
selectCurrentWeek();
}
});
$(document).on( 'mousemove','.week-picker .ui-datepicker-calendar tr',function() {$(this).find('td a').addClass('ui-state-hover'); });
$(document).on('mouseleave','.week-picker .ui-datepicker-calendar tr',function() {$(this).find('td a').removeClass('ui-state-hover'); });
#week-picker is a valid selector, as long as your input has that ID assigned. What is happening in your case is that there is JS turning your input into a datepicker, and it changes the ID of the element when it loads. As you posted from your element inspector, your input no longer has the week-picker ID, it is now dp1529862475978.
This is not uncommon, and the behavior you're getting is the expected one. If you need to make sure that you're targeting this datepicker instead of another one with the same class, you can use the name attribute:
$("input[name='week_starting']")
You should never have 2 inputs with the same name on the same page, so it's as unique as an ID. The ID you're seeing in the element inspector is probably randomly generated, so you don't want to use that.
I have jQuery Datepicker with unavailable dates:
var disabledDates = ["23.05.2017", "24.05.2017"];
$("#datepicker").datepicker({
beforeShowDay: function(date) {
var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
return [disabledDates.indexOf(string) == -1];
}
});
The only way i found to update disabledDates was to destroy datepicker, update unavailable dates and re-init.
// Destroy
$("#datepicker").datepicker("destroy");
// Update unavailable times
disabledDates = ["23.05.2017", "24.05.2017", "25.05.2017", "26.05.2017"];
// Re-init
$("#datepicker").datepicker({
beforeShowDay: function(date) {
var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
return [disabledDates.indexOf(string) == -1];
}
});
Is there a other/better way to do it?
You don't need to destroy it, simply change the beforeShowDay property, see following please:
var disableddates = ["20-05-2017", "21-05-2017"];
function DisableSpecificDates(date) {
var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
return [disableddates.indexOf(string) == -1];
}
$(function() {
$("#datepicker").datepicker({
beforeShowDay: DisableSpecificDates
});
});
$("#btn1").click(function(){
disableddates = ["01-05-2017", "02-05-2017"];
$("#datepicker").datepicker({
beforeShowDay: DisableSpecificDates
});
console.log("Disabled dates changed");
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<p>Date: <input type="text" id="datepicker"></p>
<input type="button" id="btn1" value="Change dates">
I hope it helps you, bye.
This is my code
//Put our input DOM element into a jQuery Object
var $jqDate = jQuery('input[name="jqueryDate"]');
//Bind keyup/keydown to the input
$jqDate.bind('keyup','keydown', function(e){
//To accomdate for backspacing, we detect which key was pressed - if backspace, do nothing:
if(e.which !== 8) {
var numChars = $jqDate.val().length;
if(numChars === 2 || numChars === 5){
var thisVal = $jqDate.val();
thisVal += '/';
$jqDate.val(thisVal);
}
}
});
<div style="font-family: Helvetica,Arial,sans-serif; font-size: 12px; line-height: 150%;">
<strong>HTML5 "date" input type:</strong> <input type="date" name="html5date"><br>
<strong>jQuery "date" input type mimic:</strong> <input type="text" name="jqueryDate" placeholder="dd/mm/yyyy"><br>
Key Input: <span id="keyP">null</span>
</div>
In the above code i have a textbox . In that textbox user enter date manually . It takes date format worked . But user enter day more than 31 and month 12 it not accept.How to restrict date and month by using Jquery or Javascript.
This is Jsfiddle :- https://jsfiddle.net/ChrisCoray/hLkjhsce/
You Need to add 'datePicker'as class name
$(".datePicker").datepicker({
dateFormat: 'd/mm/yy',
changeMonth: true,
changeYear: true,
firstDay: 1,
minDate: Date.parse("1900-01-01"),
maxDate: Date.parse("2100-01-01"),
yearRange: "c-90:c+150"
});
// validation in case user types the date out of valid range from keyboard : To fix the bug with out of range date time while saving in sql
$(function () {
$.validator.addMethod(
"date",
function (value, element) {
var minDate = Date.parse("1900-01-01");
var maxDate = Date.parse("2100-01-01");
var valueEntered = Date.parse(value);
if (valueEntered < minDate || valueEntered > maxDate) {
return false;
}
return !/Invalid|NaN/.test(new Date(minDate));
},
"Please enter a valid date!"
);
});
Hi i have two datetime picker and using jquery 1.7.2 in both the datetime picker i need date and time defaultly presently am getting these after click box but i need before click only . am using jsfiddle http://jsfiddle.net/srknthcse/f9raubjp/ thank you for your help
$(function() {
$('#datepicker').datepicker({
dateFormat: 'dd-mm-yy',
onSelect: function(datetext){
var d = new Date(); // for now
datetext=datetext+" "+d.getHours()+": "+d.getMinutes();
$('#datepicker').val(datetext);
},
});
});
$(function() {
$('#datepicker1').datepicker({
dateFormat: 'dd-mm-yy',
onSelect: function(datetext){
var d1 = new Date();
var d2 = new Date(d1);
var addedhour=d2.setHours(d1.getHours()+4);
// for now
datetext=datetext+" "+d2.getHours()+": "+d2.getMinutes();
$('#datepicker1').val(datetext);
},
});
});
Instead of setting datepicker to an input field set it to a div. Then use a hidden input for the value as shown on the fiddle:
http://jsfiddle.net/8ztsjcos/2/
<input type="hidden" id="to">
<input type="hidden" id="from">
$(function() {
$('#datepicker').datepicker({
dateFormat: 'dd-mm-yy',
onSelect: function(datetext){
var d = new Date(); // for now
datetext=datetext+" "+d.getHours()+": "+d.getMinutes();
$('#to').val(datetext);
},
});
});
$(function() {
$('#datepicker1').datepicker({
dateFormat: 'dd-mm-yy',
onSelect: function(datetext){
var d1 = new Date();
var d2 = new Date(d1);
var addedhour=d2.setHours(d1.getHours()+4);
// for now
datetext=datetext+" "+d2.getHours()+": "+d2.getMinutes();
$('#from').val(datetext);
},
});
});
I'm using this jQuery function with jQuery UI to generate a datepicker when the user hits one textfield:
<script>
$(function() {
var dates = $( "#from, #to" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
changeYear: true,
numberOfMonths: 1,
onSelect: function( selectedDate ) {
var option = this.id == "from" ? "minDate" : "maxDate",
instance = $( this ).data( "datepicker" ),
date = $.datepicker.parseDate(
instance.settings.dateFormat ||
$.datepicker._defaults.dateFormat,
selectedDate, instance.settings );
dates.not( this ).datepicker( "option", option, date );
}
});
});
</script>
As you can see it respond to the textfields from and to. The textfields are in my html code like:
<div class="clearfix">
<label for="from">From</label>
<input type="text" id="from" name="from" class="xlarge"/>
</div>
<div class="clearfix">
<label for="to">to</label>
At this point everything works. Later, in the same form a let the user to clone this form elements using this other code:
$(document).ready(function() {
var removeButton = 'remove';
$('#addl').click(function() {
$('div.jobitems:last').after($('div.jobitems:first').clone());
$('div.jobitems:last').append(removeButton);
$('div.jobitems:last input').each(function(){
this.value = '';
});
});
$('#remove').live('click', function() {
$(this).closest('div.jobitems').remove();
});
});
<input type="text" id="to" name="to" class="xlarge"/>
</div>
When the user clone the elements, the new ones do not respond to the function that generates the datepicker. I'm really confused about this. Here you can check the running code: http://domingo.net46.net/example/reg.php
You have to call the function that make the datapicker happen again after the append of the html elements so that the datepicker work on them because i can see that the datepicker function is called on the document ready and you have another function that append html element so you have to call the datepicker function right after you append the html elemnt.
$(DoAction);
function DoAction() {
var dates = $( "#from, #to" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
changeYear: true,
numberOfMonths: 1,
onSelect: function( selectedDate ) {
var option = this.id == "from" ? "minDate" : "maxDate",
instance = $( this ).data( "datepicker" ),
date = $.datepicker.parseDate(
instance.settings.dateFormat ||
$.datepicker._defaults.dateFormat,
selectedDate, instance.settings );
dates.not( this ).datepicker( "option", option, date );
}
});
}
$(document).ready(function() {
var removeButton = 'remove';
$('#addl').click(function() {
$('div.jobitems:last').after($('div.jobitems:first').clone());
$('div.jobitems:last').append(removeButton);
$('div.jobitems:last input').each(function(){
this.value = '';
});
DoAction();
});
$('#remove').live('click', function() {
$(this).closest('div.jobitems').remove();
});
});
The issue could be on the line that is as follows:
this.value = '';
Try changing this to become:
$(this).value = '';
Then it should work as it's creating a jQuery object
If the cloned elements have the same id as the originals, I'm not surprised that the datepicker will only act on the first elements it finds.