bootstrap-datepicker.js and jquery.maskedinput.js don't play nice - javascript

I have to use bootstrap-datepicker.js for my project but it doesn't work well with mask.
problem 1:
It you you are tabbing through fields it will auto populate the date field with today's date. Ideally it won't populate it at all.
Problem 2:
It's difficult to blank-out a the date field once it's populated.
first name: <input type="text">
birthdate: <input type="text" class="date">
city: <input type="text">
js:
$(function() {
$(".date").mask("99/99/9999");
$('.date').datepicker({
format: 'mm/dd/yyyy'
});
});
The problem is all originates from the fact that mask is populating the field with example format characters( "_ _ / _ _ / _ _ _ _" ) during focus and when the focus leaves datepicker is attempting to parse the example characters BEFORE mask has a chance to remove them. datepicker can't parse these special characters into a date therefore it is selecting today's date.
I think that if I can figure out a way to remove the example characters before bootstrap-datepicker attempts to parse them my problem would be fixed.
I would provide a jsfiddler example but I can't figure out how to add bootstrap-datepicker.js and jquery.maskedinput.js on their site.
Thanks for your help.

I stumbles across this option:
$('.date').datepicker({
format: 'mm/dd/yyyy',
forceParse: false
});
Surprising that force parse is true by default. darn bootstrap. Problem fixed.

Late answer but this was the only one that worked for me after deconstructing the sequence of events handled by both plugins (as of this date).
var $date = $('.date');
$date.datepicker({
format: 'mm/dd/yyyy'
});
$date.mask("99/99/9999");
$date.on('keyup', function(){
if ($date.val() == '__/__/____'){
// this only happens when a key is released and no valid value is in the field. Eg. when tabbing into the field, we'll make sure the datepicker plugin does not get '__/__/____' as a date value
$date.val('');
}
});
Long Explanation
Turns out that the datepicker plugin calls an update function on keyup, which in this case is the keyup event triggered when you release the TAB key. This update function calls a DPGlobal.parseDate() function that roughly behaves like this:
DPGlobal.parseDate(''); // returns new Date(); aka. now
DPGlobal.parseDate('10/10/1983'); // returns a Date instance that points to 10/10/1983
DPGlobal.parseDate('__/__/____'); // is generated by the maskedinput plugin and is interpreted as an ilegal date, so the datepicker goes back to the origin of unix time, 1970
This could easily be fixed by changing the parseDate function on the datepicker lib but this is a big no no if you want to keep your code maintainable. We are left then with a hackish way to intercept the foul value and correct it before maskedinput hands it over to the datepicker.
Hope it helps!

Try use other class name to datepicker and mix in your html
$(function() {
$(".date").mask("99/99/9999");
$('.date2').datepicker({
format: 'mm/dd/yyyy'
});
});
birthdate: <input type="text" class="date date2">

Related

Defaultvalue on date select jquery datetimepicker

Using Jquery Timepicker . Is it possible to do so, that when I select a date, then time is automatically set to 23.59, but if I change the time manually then it keeps the time value?
I dont want the datetime showing until i select a date or time. But currently all the solutions that I have found are about setting a default value that you can see when the element is loaded.
<input size="15" class="timePicker" name="name" id="id" style="width: 100%" />
jQuery('.timePicker').datetimepicker({
dateFormat: 'dd.mm.yy'
});
SOLUTION
Apparently it turns out, that in the timepicker sourcecode options hour and minute are ignored and not used. Solution for that would be to open up the timepicker.js, find the _newInst function and then either change the corresponding lines, or you could just override the prototype method with a method that has the required fixes.
So simple just change the default timepicker values before calling the time picker as below :
$.timepicker._defaults.hour = 23;
$.timepicker._defaults.minute = 59;
var jq = jQuery('.timePicker').datetimepicker({
dateFormat: 'dd.mm.yy'
});
see this working Fiddle .

jquery datepicker defaultdate will not automatically set to next available date when graphical calendar is persistent on a page

The jquery datepicker defaultdate will not automatically set to next available date when the graphical calendar is persistent on a page. the initial date the calendar selects can be a date that i have disabled. Many suggestions on workaround work when the calendar is a popup to an input field, but do not work when the calendar is persistently shown as a div. doesn't matter if the dates disabled are by noWeekends, by the day of week, or individually set days, the initial date value can be a disabled and unclickable date. I am using the alternate1 input field (which i normally hide) to pass data onto a PHP page. What i have almost works, but the next available date shows as highlighted when minDate happens to land on an available date, but when minDate lands on an unselectible date, the highlight is hidden. The temporary fix i used of setDate null - clears the initial selection value regardless of the highlight, so a visitor may think the a date is already selected when it is not. My PHP page reports back to the visitor that they have to go back and actually select a date. My use of datepicker is geared toward mobile, so popup or flyout calendar to make use of well known workarounds is unfavorable, the calendar GUI needs to be persistent on the page. To recreate my issue for yourself, on the jsfiddle, comment out the last javascript line, disallow a date mid-week in the var selections, and then set the minDate so that it will land on the disallowed date. you'll notice the alternate1 input gets prefilled with the disallowed date.
html code:
<div id="dp1"></div>
<input type="text" id="alternate1" name="alternate1"/> <!-- style="display:none;" this is the field that passes on to php -->
javascript code:
var selections = [
"2017-07-29",
"2017-07-30",
"2017-08-05",
"2017-08-06",
"2017-08-12",
"2017-08-13",
"2017-08-19",
"2017-08-20",
"2017-08-26",
"2017-08-27",
"2017-09-02",
"2017-09-03",
"2017-09-04",
"2017-09-09",
"2017-09-10",
"2017-09-16",
"2017-09-17",
"2017-09-23",
"2017-09-24",
"2017-09-30",
"2017-10-01",
"2017-10-07",
"2017-10-08",
"2017-10-09",
"2017-10-14",
]
function bansingle(date) {
var excerpt = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [ selections.indexOf(excerpt) == -1 ]
}
// somehow combine this function later.
//function bandow(date) {
// var day = date.getDay();
// return [(day != 0 && day != 6)];
// }
$('#dp1').datepicker({
beforeShowDay: bansingle,
altField:'#alternate1',
altFormat: 'm-d-yy',
fielddateFormat: 'm-d-yy',
minDate: "+0d",
//maxDate: "+1m", // set latest selectable date
});
$('#dp1').datepicker("setDate", null); //clears alternate1 input field value
Here is the jsfiddle it does contain more dates and a little CSS. I recommend opening it in a new tab, to be able to return to this page after editing code.
the progress of my other question here has negated the need for an answer to this question. pursuing multiple changes to input, styling, and options - will workaround this question's problem.

How to call a function on selection of date in html5 and bootstrap picker

I had a html5 input field of type="datetime" which shows a date picker.Now on click of any date in the date picker,I want to call a function.
If Iam using ng-click ,it is getting called once i click in textfield.Even ng-change is not working.But I want to call the function after selecting the date in datepicker..Which event can be used to achieve this.Can someone help.
<input class="form-control" type="datetime" date-time auto-close="true" view="date"
min-date="{{today}}" min-view="date" maxlength="10" format="dd/MM/yyyy"
ng-model="$ctrl.DateInput" required="true" ng-change="$ctrl.checkdate()">
js
$scope.today= new Date().toISOString().split('T')[0];
this.checkdate=function(){
alert("hi");
Notification.error('Please select proper date');
};
You could watch the variable and than take action on change:
$scope.$watch("DateInput", function(newValue, oldValue) {
//..do something
});
First, you should use the datetime-local input type, this is supported by AngularJS, not datetime.
Second, the problem comes from the input\[datetime-local\] API of AngularJS. The ngModel value must be a valid Date object, this is what prevents the ng-change directive from firing.
You could set the DateInput property to a new date using this.DateInput = new Date(), however the value displayed will be a complete date string (hours, seconds, ms).
You may try finding a workaroung by applying a kind of filter on ngModel, but it's not natively permitted by Angular and will not be easy.
If you're stuck, you can use the great Angular-UI for Bootstrap library and its datepicker directive.

How do you prevent bootstrap-datepicker from clearing existing value from input if no date is selected?

I have have a div with a user's date of birth pre-populated with php:
<div id="datepicker" class="input-group date">
<label for="dob">Date of Birth</label> <input type="text" class="form-control" id="dob" name="dob" value="<?php $date = new DateTime($this->swimmers->dob); echo $date->format('d/m/Y');?>"><span class="input-group-addon"><i class="glyphicon glyphicon-th"></i></span>
</div>
The javascript:
<script>
$('.container .input-group.date').datepicker({
startDate: "01/01/1900",
endDate: "01/01/2100",
format: "dd/mm/yyyy",
autoclose: true,
todayHighlight: true
});
</script>
Bootstrap is setup and working correctly however, when the "dob" input gets and loses focus without making a date selection it clears the value that was pre-populated.
This however doesn't happen if a date has been selected via the datepicker and then the input gets and loses focus.
How can the pre-populated value be kept in the field if someone clicks in it?
Edit: The first time you make a date selection, it clears the pre-populated value but doesn't insert the selected date until you make a date selection a second time.
Update: Working code updated!
Set Force parse value to false:
forceParse: false
$(".applyDatepicker").datepicker({
forceParse: false
});
I am not sure about its working in php but for mvc I got the same problem that Bootstrap would erase the value if the control gets and loses focus without making a date selection.
I found that Bootstrap erases the value as it doesn't recognize the value set by
$('#dtControl').val(nextMonth);
I am working with bootstrap v3.1.1 and the following code worked for me
$('#dtControl').datepicker('setDate', nextMonth);
to populate the datepicker control. This way Bootstrap recognizes the date and doesn't erase it if control gets and loses focus
Can't tell for sure without more of an example but the problem is probably that the $this->swimmers->dob string you are giving to the input is not recognised as a date format by bootstrap-datepicker. You can define the date format it uses by adding the data-date-format attribute to your input.
For example if you were using a MySQL formatted date or PHP's DateTime object with $date->format('Y-m-d') you could use:
<div id="datepicker" class="input-group date">
<input type="text" class="form-control" id="dob" name="dob" value="<?php echo $this->swimmers->dob;?>" data-date-format="yy-mm-dd"><span class="input-group-addon"><i class="glyphicon glyphicon-th"></i></span>
</div>
I had a similar problem when a user clicked on the same date twice. The field would "toggle" between the date clicked on and a blank field. I basically didn't want it to be empty at any stage, so here's how I got around that, partly thanks to Waqas's answer:
var datepickerContainer = $('#datepicker');
datepickerContainer.datepicker({
startDate: "01/01/1900",
endDate: "01/01/2100",
format: "dd/mm/yyyy",
autoclose: true,
todayHighlight: true
}).on('show', function() {
datepickerContainer.datepicker.currentDate = $('input#dob').val(); //update this instance with the current value
}).on('changeDate', function(event) {
var newDate = $('input#dob').val();
if (newDate == '' || newDate == null) { //check if the new value is empty - if it is, then just set it back to the last known date for this instance
datepickerContainer.datepicker('setDate', datepickerContainer.datepicker.currentDate);
}
});
That keeps it relatively self-contained, by storing the last date value in that instance of the datepicker and results in no clearing of the input.
I know you solved this problem, but I figured this snippet might come in handy for someone else in a similar situation.
When jQuery calls a handler, the this keyword is a reference to the element where the event is being delivered. Futhermore, a non empty string will evaluate to true. Based on these facts, simply do a check in the event handler. See sample code below.
.find( 'input[name=startDate]' )
.datepicker( {format: 'dd-mm-yyyy'} )
.on( 'changeDate', function() {
if( this.value ) {
<< do something >>
}
});
NOTE: For efficiency and readability in code sample above, the DOM property value is checked, instead of wrapping this in a jQuery object and calling val() on it ( $( this ).val() ). This is a minor improvement, but it's a good practice to be as compact/simple as possible.
Another solution is to define the options at the global level:
$('.datepicker').datepicker();
$.fn.datepicker.defaults.format = 'dd/mm/yyyy';
$.fn.datepicker.defaults.startDate = "0";
$.fn.datepicker.defaults.language = "es";
$.fn.datepicker.defaults.autoclose = true;
$.fn.datepicker.defaults.todayHighlight = true;
$.fn.datepicker.defaults.todayBtn = true;
$.fn.datepicker.defaults.weekStart = 1;
Now, when use update method, datepicker don't lost options.
$('#dob').datepicker('update', '2011-03-05');
You can use like this. Although for me it was working by simply passing value to element by using .val() function.
Reference URL.
https://bootstrap-datepicker.readthedocs.io/en/latest/methods.html

Is there a JavaScript way to set the time for this jQuery timepicker plugin?

I would like to set the current date/time to populate automatically into the input textbox according to the same format used by this timepicker plugin:
http://trentrichardson.com/examples/timepicker/
The plugin assumes that you want the input text field to appear blank until the user interacts with it.
$('#example2').datetimepicker({
ampm: true
});
But I want the input text field to already contain the current date and time:
05/16/2011 04:00 am
The only way I can see to do this at the moment is using my server-side scripting language.
But ideally there should be a way to do this with JavaScript or jQuery?
In the link you provided, it shows you how to specify the time:
$('#example7').datetimepicker({
hour: 13,
minute: 15
});
A quick way would be to set the value of the text box within the HTML markup, e.g.
<input type="text" id="example7" value="05/16/2011 04:00" />
Or it could be done with JQuery:
$('#example7').val("05/16/2011 04:00");
Use
$('#yourcontrol').datetimepicker('setDate', new Date());
to set the control with current date and time.

Categories

Resources