javascript datepicker detect changed value in input field - javascript

I've got simple date picker based on mootools (http://www.monkeyphysics.com/mootools/script/2/datepicker)
This is not jQuery datepicker, it's event triggers don't work.
I'd need to calculate days and other things once dates are picked, calculation works fine, I need it to fire after user decides to change dates, I've tried all event handlers I could find, they all work if you press enter or click another field, but it should recalculate right after clicking (picking) the date.
<input type="text" name="arrival" value="2016-10-05" title="" class="fromdate">
<input type="text" name="departure" value="2016-10-08" title="" class="todate">
<input type="text" name="addnight" value="" title="" class="calculated">
<script type="text/javascript">
$("select, input, .datepicker_dashboard").on("change paste keyup blur click mouseup hover focus focusout", function() {
var calculus = daydiff(parseDate($('.fromdate').val()), parseDate($('.todate').val()));
if (calculus<0) {var calculus=0;}
$(".calculated").val(calculus);
}
</script>

Reading the documentation (linked by yourself) tells me that you are able to set an onSelect handler in the options while creating the datepicker with new DatePicker(input-target-selector [, options-object]);
onSelect
Event hook triggered when a date is selected. (v1.16+: comes with 1
argument, a standard javascript Date object representing the selected
Date)

Try this. I got the answer from the link listed below
Trigger function when date is selected with jQuery UI datepicker
$("#dt").datepicker({
onSelect: function(dateText, inst) {
var date = $(this).val();
var time = $('#time').val();
alert('on select triggered');
$("#start").val(date + time.toString(' HH:mm').toString());
}
});

Related

Event listener when another event changes my input value

I have an input with datepicker class on it, which looks like this:
<input class="ui-calendar hasDatepicker" type="text" name="date" id="date">
I need to cover all scenarios when this input value is changed. So I have a .datepicker onSelect (used when I select the date via datepicker calendar) and simple onChange (used when I enter the date by keyboard) events:
$('#date').datepicker({
onSelect: function() {
console.log('datepicker onSelect event');
}
});
and
$('#date').on('change', function() {
console.log('onChange event');
});
Now the problem is that I have separate button:
Set date
And this setDate function changes the value of my datepicker input.
How do I catch this setDate event without putting any code into setDate function itself? I tried adding listener on my datepicker input but it only catches values I enter by keyboard.
Firstly, don't use on* event attributes, attach your event handlers unobtrusively.
Secondly, you should make setDate() change the date through the datepicker() library, then you'll get this behaviour for free:
Set date
$('.set-date').click(function(e) {
e.preventDefault();
$("#date").datepicker("setDate", $(this).data('date1'));
});
Alternatively you can set the val() on the input and manually trigger() a change event.
$('.set-date').click(function(e) {
e.preventDefault();
$('#date').val($(this).data('date1')).trigger('change');
});

Set datepicker value to empty

I have a list of form for user to input. All the form have the same input that user need to fill in. And there is a next button to go to the next form. So basically the flow is like this: User fill in the first form, click next button will go to second form and so on. So i just reuse the input for all the form. I do a save first after that reset the input field for the next form.
Everything work fine except the datepicker field, I'm using Kendo Datepicker. I reset it like this:
$('#datepicker').data('kendoDatePicker').value("");
Even thought the field show nothing, but when i save, it always set the previous input date into it.
So anyone know how to solve this?
Simply use $("#datepicker").val('');
See JsFiddel http://jsfiddle.net/x4dA9/775/
ADD:
Using Model: jsFiddel
<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('');
});
After resetting the Kendo UI jquery datepicker with the line...
datepicker.value('')
the input mask is lost.
To keep the input mask, reset the format option on the control...
$("#clearSystemUsageToBtn").click(function (e) {
var datepicker = $("#DateToK").data("kendoDatePicker");
datepicker.value('');
datepicker.setOptions({ format: "dd/MM/yyyy" });
});

Date range validation with jQuery UI datepicker: order of events

I'm using Jörn Zaefferer's jQuery validation plugin alongside the jQuery UI datepicker. I've created a set of custom rules for validating that a start date is prior to an end date.
The issue I have is that when I have an invalid range and use the datepicker UI to change a date to make the range valid, I see the validation running with the old values (and thus keeping the fields invalidated) prior to the onSelect callback firing for the datepicker.
I would expect that the datepicker would update the input's value when the user selects, and that any validation code would run when that happens and see the new value. But that doesn't seem to happen.
I've tried initializing the datepicker before initializing validation in hopes that the order the events were wired in would make the difference, but you can see it hasn't helped.
Here's the fiddle
To reproduce the issue, enter the 15th of a given month in the start, and the 7th of the same month in the end. Click the start field and then click or tab out to trigger validation. The fields correctly invalidate. Now click the start field and select the 1st of the same month. Note what's output at this point on the console.
The code, for reference:
HTML
<form id="daterange-form">
<div class="form-group">
<label for="startDate">Start Date</label>
<input type="text" id="startDate" name="startDate" class="validDate form-control" />
</div>
<div class="form-group">
<label for="endDate">End Date</label>
<input type="text" id="endDate" name="endDate" class="validDate form-control" />
</div>
<button type="submit" class="btn">Submit</button>
</form>
JavaScript
// Custom Rules
$.validator.addMethod('dateBefore', function(value, element, params) {
// if end date is valid, validate it as well
console.log('dateBefore', value, element, params)
var end = $(params);
if (!end.data('validation.running')) {
$(element).data('validation.running', true);
// The validator internally keeps track of which element is being validated currently. This ensures that validating 'end' will not trample 'start'
// see http://stackoverflow.com/questions/22107742/jquery-validation-date-range-issue
setTimeout($.proxy(
function() {
this.element(end);
}, this), 0);
// Ensure clearing the 'flag' happens after the validation of 'end' to prevent endless looping
setTimeout(function(){
$(element).data('validation.running', false);
}, 0);
}
return this.optional(element) || this.optional(end[0]) || new Date(value) < new Date(end.val());
}, 'Must be before its end date');
$.validator.addMethod('dateAfter', function(value, element, params) {
// if start date is valid, validate it as well
console.log('dateAfter', value, element, params)
var start = $(params);
if (!start.data('validation.running')) {
$(element).data('validation.running', true);
// The validator internally keeps track of which element is being validated currently. This ensures that validating 'end' will not trample 'start'
// see http://stackoverflow.com/questions/22107742/jquery-validation-date-range-issue
setTimeout($.proxy(
function() {
this.element(start);
}, this), 0);
// Ensure clearing the 'flag' happens after the validation of 'end' to prevent endless looping
setTimeout(function() {
$(element).data('validation.running', false);
}, 0);
}
return this.optional(element) || this.optional(start[0]) || new Date(value) > new Date($(params).val());
}, 'Must be after its start date');
// Code setting up datepicker and validation
$('#startDate, #endDate').datepicker({
onSelect: function(dateText, inst) {
console.log('onSelect', dateText, inst)
}
});
$('#daterange-form').validate({
debug: true,
rules: {
startDate: {dateBefore: '#endDate'},
endDate: {dateAfter: '#startDate'}
}
});
Side note: the timeouts and proxy calls in the rules are because this version of the library internally assumes serial validation. If you try to validate another field in the middle of a rule, Bad Things happen. The validation.running semaphore code is to prevent infinite looping.
I've tried initializing the datepicker before initializing validation in hopes that the order the events were wired in would make the difference, but you can see it hasn't helped.
The order should/would not matter, because as you know, it's only the initialization, not the implementation.
I would expect that the datepicker would update the input's value when the user selects, and that any validation code would run when that happens and see the new value. But that doesn't seem to happen.
The date-picker does indeed update the input value, however validation is not triggered because that's not a normal event the validation plugin is expecting. Validation is only triggered on the submit, keyup and focusout events, none of which happen when using .datepicker().
So you can programmatically force a validation test using the .valid() method whenever you wish...
$('#startDate, #endDate').datepicker({
onSelect: function(dateText, inst) {
$(this).valid();
}
});
DEMO: jsfiddle.net/nkvpsumq/2/
.valid() can be attached to an individual input, select, textarea, or an entire form. When attaching to a selector that contains more than one object, you must enclose this method using a jQuery .each(). In your case, the .each() is not needed because you're already programmatically re-triggering validation on the opposing field using this.element() within your custom rules. Now that you know about triggering the .valid() method via a .datepicker() event, you may wish to refactor the rest of your code a bit.
Here's the code I ended up using to solve the issue and keep it DRY.
$.datepicker._selectDate_super = $.datepicker._selectDate;
$.datepicker._selectDate = function(id, dateStr) {
$.datepicker._selectDate_super(id, dateStr);
$(id).valid();
};
(or if you prefer es6 and ASI ;)
$.datepicker._selectDate_super = $.datepicker._selectDate
$.datepicker._selectDate = (id, dateStr) => {
$.datepicker._selectDate_super(id, dateStr)
$(id).valid()
}

jQuery - how to "activate" input when I move on it with pressing "tab" key?

I have a form and when I move on an input that contains where the user is supposed to enter a date (after clicking into it, I fire datetime picker from jQuery-UI), nothing happen.
When I click into the field, the datatime picker is fired, that's fine. But when I move onto this input by pressing the tab key, the datetime picker is not activated. How do I activate it?
I tried
$(function() {
$('body').on('blur','.date_field', function(e) {
$(this).datepicker({dateFormat: 'yy-mm-dd'}).focus();
}
});
But it doesn't work. I also tried to use keypress or keydown and comparing the key-codes, but it doesn't work neither.
How to activate the datetime by moving on an input by pressing the tab key?
EDIT:
I tried also bind with no success.
Thank you.
js at Question is missing closing ) at event handler. Initialied .datepicker() before blur event. Added tabindex="1" to input element. Actually, blur event is not needed, and would appear to recursively add focus to input element.
$(function() {
$(".date_field").datepicker({dateFormat: "yy-mm-dd"});
//$("body").on("blur",".date_field", function(e) {
// $(this).focus();
//})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
Date: <input type="text" class="date_field" tabindex="1">

Datepicker change date format and submit form

I have found one useful range datepicker (with only one input field):
http://bseth99.github.io/projects/jquery-ui/4-jquery-ui-datepicker-range.html
I have changed the format from 'mm/dd/yy' to 'yy-mm-dd', it works so far user selects two different dates. If the user chooses the same date for start and end, the format is still the default - 'mm/dd/yy'. How can i change this ?
The second part of my problem is to submit the form. I have tried that, but it doesnt work:
.datepicker({
onChange: function () {
$('#exchange_search').submit();
}
})
I have found how to submit the form. Still remains the problem with the single date format.
Here is the solution if someone needs it:
onAfterUpdate: function ( inst ) {
$('<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" data-handler="hide" data-event="click">Done</button>')
.appendTo($('#jrange div .ui-datepicker-buttonpane'))
.on('click', function () {
$('#jrange div').hide();
$('#exchange_search').submit();
});
}

Categories

Resources