Datepicker has this function which allows you to ship the date into an alternative input with an alternate date format. In my program, I’m hiding the datepicker input and trigger open the calendar with a button. How do I get the date from this alternate input?
My code
/*
open calendar
*/
$(document).on('click','.openDatePicker',function(){
$('#popupDatepicker').datepicker({
changeMonth: true,
changeYear: true,
altField: "#alternateDateField",
altFormat: "DD, d MM, yy"
});
$('#popupDatepicker').show().focus().hide();
})
/*
get date from alternate field
*/
$(document).on('change','#alternateDateField',function(){
var fulldate = $('#alternateDateField').val();
console.log(fulldate)
})
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<button class="openDatePicker">Calendar</button>
<input type="text" style="display: none;" id="popupDatepicker">
<input type="hidden" id="alternateDateField" size="30">
2
Answers
altField
Datepicker set value for input field but not trigger change event. So, you cannot catch the input’s change event.Try catching the datepicker’s
onSelect
event instead:The
change
event does not fire unless the input was changed by the user interacting with the browser UI. It does not fire if the value is changed by software. This is by design and is not a jQuery behavior, but a browser behavior.So you need to manually trigger the event by yourself. There are two ways to do this:
onSelect
option to trigger achange
event manually. (best approach)setInterval
method to periodically check whether the hidden input’s value is changed. (alternate approach)See the following example using first approach:
References:
onSelect
:setInterval()
: