It's maybe old question to add more then date-picker's on the same page. But I have a different case here.
used library
https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js
Here is the script for the datepicker
<script>
$(document).ready(function () {
$('.datepicker').datepicker({
keyboardNavigation: false,
forceParse: false,
todayHighlight: true
});
});
</script>
now multiple date-picker will work fine on the same page.
{!! Form::text('expiry_date', null, ['data-format'=>'D, dd MM yyyy', 'class'=>'form-control datepicker', 'placeholder'=>'yyyy-mm-dd']) !!}
{!! Form::text('expiry_date', null, ['data-format'=>'D, dd MM yyyy', 'class'=>'form-control datepicker', 'placeholder'=>'yyyy-mm-dd']) !!}
but the second datepicker here comes from extending form script
<script>
let counter = 1;
let limit = 10;
function addInput(divName) {
if (counter === limit) {
alert("You have reached the limit of adding " + counter + " inputs");
} else {
let newdiv = document.createElement('div');
newdiv.innerHTML = '<div class = "col-md-12"> <h4>Package ' + (counter + 1) + ' </h4> ...<div class="col-sm-6"><div class="form-group"><div id="date-popup2" class="input-group date">{!! Form::text("expiry_date", null, ["data-format"=>"D, dd MM yyyy", "class"=>"form-control datepicker", "placeholder"=>"yyyy-mm-dd"]) !!}<span class="input-group-addon"><i class="fa fa-calendar"></i></span></div></div></div>...';
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
</script>
When the second datepicker populate it dose't work. Any idea.
It's because you're initiating the .datepicker(), before you have rendered the second datepicker object.
Maybe try something similar to this:
$(function() {
$(this).datepicker();
$('#date').append('<p>Other Date: <input onfocus="dateme(this);" type="text" class="datepicker"></p>')
});
function dateme(x){
$(x).datepicker();
}
Just to explain what's going on here, I append a new datepicker input, which has an onfocus="" attribute, which calls a function containing the .datepicker function when the input is in focus.
Codepen Example: https://codepen.io/lthomas122/pen/XQyOMm
For fast isolation
$('.datepick').each(function(){
$(this).datepicker({
keyboardNavigation: false,
forceParse: false,
todayHighlight: true
});
// apply the rest
});
this here it will keep it isolated
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 am trying to disable future hours within today using disabledTimeIntervals but it doesn't seem to work.
What I need to do is disable future hours in timepicker for today only, because disabling dates I can do with maxDate.
<input class="form-control input-sm pull-left " id="dp" placeholder="To" type="text">
$('#dp').datetimepicker({
maxDate: '0',
disabledTimeIntervals: [[moment(), moment().hour(24).minutes(0).seconds(0)]],
format: 'm/d/Y H:i A',
timepicker: true,
});
JSFIDDLE: https://jsfiddle.net/3oxmccjq/1/
You can use maxTime option and function onChangeDateTime to set the minTime according to the selected date.
The comparison between dates is up to you :-)
var today = new Date();
var options = {
maxDate: new Date(),
maxTime: new Date(),
disabledTimeIntervals: [
[moment(), moment().hour(24).minutes(0).seconds(0)]
],
format: 'm/d/Y H:i A',
timepicker: true,
onChangeDateTime: function(date) {
// Here you need to compare date! this is up to you :-)
if (date.getDate() === today.getDate()) {
this.setOptions({maxTime: new Date()});
} else {
this.setOptions({maxTime: false});
}
}
};
$('#dp').datetimepicker(options);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.4/build/jquery.datetimepicker.full.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.2.1/moment.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.4/jquery.datetimepicker.css" rel="stylesheet" />
<input class="form-control input-sm pull-left " id="dp" placeholder="To" type="text">
The datetimepicker you are using in your jsfiddle have no options as disabledTimeIntervals and that's why it is not working. You should use disabledMinTime & disabledMaxTime
As for the solution I am guessing you want to disable all future hours for today but still want to allow future dates with all the possible time. Here is a jsfiddle for same :-
https://jsfiddle.net/sahilbatla/zpzL2po3/
Code looks like this :-
var today = new Date();
var todayEndOfDay = new Date().setHours(23,59,59,999);
$('#dp').datetimepicker({
disabledMinTime: today,
disabledMaxTime: todayEndOfDay,
format: 'm/d/Y H:i A',
timepicker: true,
onChangeDateTime: function(date) {
if (date.getDate() !== today.getDate()) {
this.setOptions({disabledMinTime: false, disabledMaxTime: false})
} else {
this.setOptions({disabledMinTime: today, disabledMaxTime: todayEndOfDay})
}
}
});
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!"
);
});
I have a daterange picker based on http://www.daterangepicker.com 's daterange picker and I want to set the start date to empty. This will work for what I want to do.
I'm using an text input field to get the dates
</span><input type="text" class="form-control" id="reservation" />
On the site there is an example of setting "Input Initially Empty" but I couldn't get it to work. Basically I don't know where to set it as it seems.
My daterange picker is inside a partial view and it called by another view. Page scripts are set in the view which calls the partial one. On the daterangepicker.js script I found these lines;
//default settings for options
this.parentEl = 'body';
this.element = $(element);
this.startDate = moment().startOf('day');
this.endDate = moment().endOf('day');
this.minDate = false;
this.maxDate = false;
this.dateLimit = false;
this.autoApply = false;
this.singleDatePicker = false;
this.showDropdowns = false;
this.showWeekNumbers = false;
this.timePicker = false;
this.timePicker24Hour = false;
this.timePickerIncrement = 1;
this.timePickerSeconds = false;
this.linkedCalendars = true;
this.autoUpdateInput = true;
this.ranges = {};
As far as I can tell they are based on moment.js. I tried manipulating this.startDate but couldn't manage to set it to a blank value. using this.startdate = null made the whole date range picker stop working so I guess I need something like empty date equivalent of moment.js. Or something entirely different.
Can anyone show me how to do it?
Input Initially Empty
<input type="text" name="datefilter" value="" />
<script type="text/javascript">
$(function() {
$('input[name="datefilter"]').daterangepicker({
autoUpdateInput: false,
locale: {
cancelLabel: 'Clear'
}
});
$('input[name="datefilter"]').on('apply.daterangepicker', function(ev, picker) {
$(this).val(picker.startDate.format('MM/DD/YYYY') + ' - ' + picker.endDate.format('MM/DD/YYYY'));
});
$('input[name="datefilter"]').on('cancel.daterangepicker', function(ev, picker) {
$(this).val('');
});
});
</script>
or
//daterangepickers
//moment.locale('tr');
moment.locale("#SessionHelper.CurrentLanguageTwoChar");
$(".date-control").daterangepicker({
singleDatePicker: true,
showDropdowns: true,
//timePicker: true,
//timePicker24Hour: true,
//timePickerSeconds: true,
minYear: parseInt(moment().subtract(10, 'years').format('YYYY'),10),
maxYear: parseInt(moment().add(10, 'years').format('YYYY'), 10),
autoUpdateInput: false,
singleClasses: "",
locale: {
//format: 'DD.MM.YYYY HH:mm:ss'
//format: 'DD.MM.YYYY'
}
});
$('.date-control').on('apply.daterangepicker', function (ev, picker) {
$(this).val(picker.startDate.format('L'));
});
$('.date-control').on('cancel.daterangepicker', function (ev, picker) {
$(this).val('');
});
http://www.daterangepicker.com/#example5
https://github.com/dangrossman/daterangepicker/issues/815
autoUpdateInput: false
function (chosen_date) {
$('.form-datetime').val(chosen_date.format('YYYY-MM-DD'));
}
I solved this issue using this....I hope this issue could help you.
Input Tag
<div class="form-group">
<label>Due date:</label>
<div class="input-group">
<input type="text"
class="form-control float-right"
id="duetime"
name="due_time"
autocomplete="off"
/>
</div>
</div>
script
<script>
$(function(){
$("#duetime").daterangepicker({
autoUpdateInput: false,
minYear: 1901,
showDropdowns: true,
singleDatePicker: true,
timePicker: true,
timePicker24Hour: false,
timePickerIncrement: 05,
drops: "up",
locale: {
format: 'MM/DD/YYYY hh:mm A'
}
}).on("apply.daterangepicker", function (e, picker) {
picker.element.val(picker.startDate.format(picker.locale.format));
});
});
</script>
Note: I found this from this source https://github.com/dangrossman/daterangepicker/issues/815#issuecomment-493323964
To set default value of date range picker to null,
Inside your function set autoUpdateInput to false
autoUpdateInput: false,
for the daterangepicker include from date and to date
please flowing this code set start date to blank
$('.form-datetime').daterangepicker({autoUpdateInput: false}, (from_date, to_date) => {
console.log(from_date.toDate(), to_date.toDate());
$('.form-datetime').val(from_date.format('DD/MM/YYYY') + ' - ' + to_date.format('DD/MM/YYYY'));
});
Thanks.
I was trying to get date picker on clone rows in the table.But it is not happening
my table code as follows:
<input type="text" class="form-control dp4 dob4" autocomplete="off" name="date[]" required>
<input type="button" class="btn btn-default addButton" value="Add" />
and javascript for clone row as follows:
$(function() {
$("#table-data").on('click', 'input.addButton', function() {
var $tr = $(this).closest('tr');
var allTrs = $tr.closest('table').find('tr');
var lastTr = allTrs[allTrs.length - 1];
var $clone = $(lastTr).clone();
$clone.find('td').each(function() {
var el = $(this).find(':first-child');
var id = el.attr('id') || null;
if (id) {
var i = id.substr(id.length - 1);
var prefix = id.substr(0, (id.length - 1));
el.attr('id', prefix + (+i + 1));
el.attr('name', prefix + (+i + 1));
}
});
$clone.find('input:text').val('');
$tr.closest('table').append($clone);
});
$("#table-data").on('change', 'select', function() {
var val = $(this).val();
$(this).closest('tr').find('input:text').val(val);
});
});
and my date picker code as follows:
$('.dob4').datepicker({
format: 'dd-mm-yyyy',
startDate: '-0m',
autoclose: true
});
Please help to solve this issue.
Thanks.
There is workaround to it,
How it Works:
Need to remove the class hasDatepickerfrom the cloned elements,because this is what is preventing the datepicker from getting attached to the specific element.
Need to remove the id attribute from each of the cloned elements else .datepicker() will assume that datepicker is added to this element.
After that call .datepicker() on cloned element.
JS Code:
$("#table-data").on('click', 'input.addButton', function () {
...
$clone.find('.dob4').removeAttr('id').removeClass('hasDatepicker');
$clone.find('.dob4').datepicker({
format: 'dd-mm-yyyy',
startDate: '-0m',
autoclose: true
});
...
});
Live Demo # JSFiddle