I am using Bootstrap datetimepicker in a form insider my Meteor.JS app in order to have two time picker elements. Below is the code I have so far which detect the onChange event for each of the two time picker elements in my form but I can't figure out how to get the selected time? So can someone please tell me how to do so? Thanks
$('.set-start-time').datetimepicker({
pickDate: false
});
$('.set-end-time').datetimepicker({
pickDate: false
});
$('.set-end-time').on("dp.change",function (e) {
var now = $('.set-start-time').data("DateTimePicker").getDate();
var then = $('.set-end-time').data("DateTimePicker").getDate();
//Above code won't return time...
});
I hope this helps some one.
HTML
<div name="startTime" class="input-group time">
<input class="form-control" type="text" value="" >
<span class="input-group-addon"><i class="fa fa-clock-o"></i></span>
</div>
JS
$('.time').datetimepicker({
format: 'LT'
}).on("dp.change",function(e){
var date = e.date;//e.date is a moment object
var target = $(e.target).attr('name');
console.log(date.format("HH:mm:ss"))//get time by using format
})
e.date is a moment object thus time can derived by using format("HH:mm:ss")
Related
I have a booking form that requires two dates, so I'm using the built in option that Bootstrap datepicker has (it consists on calling the datepicker function on the father element that contains the inputs), to show the daterange selected, this is my HTML:
<div class="grupo vip-fechas input-daterange">
<div class="barra verde"> <span>¿Cuándo llegas?</span></div>
<input type="text" class="input calendario" id="entrada_input" name="entrada_input" placeholder="Selecciona una fecha">
<input type="hidden" id="fecha_inicio" name="fecha_inicio">
<div class="barra verde"> <span>¿Cuándo te vas?</span></div>
<input type="text" class="input calendario" id="salida_input" name="salida_input" placeholder="Selecciona una fecha">
<input type="hidden" id="fecha_fin" name="fecha_fin">
</div>
This is my Javascript code:
$(document).ready(function(){
iniciarFechas();
});
function iniciarFechas(){
var date = new Date();
var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
var date_hidden;
$('.vip-fechas.input-daterange').datepicker({
weekStart: 1,
maxViewMode: 1,
language: "es",
startDate: today,
disableTouchKeyboard: true,
format: {
toDisplay: function(date, format, language) {
var fecha = moment(date).add(1,"day");
date_hidden = fecha;
return fecha.format("dddd DD [de] MMMM, YYYY");
},
toValue: function(date, format, language) {
var fecha = moment(date).add(1,"day");
return moment(fecha).format("DD/MM/YY");
//return moment(date, ["DD.MM.YYYY", "DDMMYYYY"]).toDate();
}
},
}).on("changeDate", function(e){
var fecha_formateada = moment(date_hidden).format("DD/MM/YY");
$(this).next().val(fecha_formateada);
});
}
The daterange works correctly but I want to store the formatted date inside the hidden inputs, as you can see, the format that I want is this: ...format("DD/MM/YY"); but what I get is the display format: format("dddd DD [de] MMMM, YYYY"), also I noticed that $(this) value within this line: $(this).next().val(fecha_formateada); refers to the container div, and not the input that has changed value, so how can I save the date as I want inside the hidden inputs?
I'm not sure what your problem is but by looking at your code I can only guess that you might be in the middle of a race condition.
You're setting the date_hidden variable in Datepicker.toDisplay and then reading from it in the changeDate custom event.
Put a debugger or a console log in both callbacks to make sure you're not in the middle of a race condition.
As for setting the formatted value in the input fields, well I can see in your HTML code that you have selectors that you can use, like the hidden field's ID for example.
Another thing I'd suggest is, instead of setting and reading the date_hidden field in those different callbacks, just call $('#elementID').datepicker('getDate') in the changeDate event handler and do all the transformations you need there, then extract that code and put it in a separate function.
I am working on an application in which i want to restrict user to manually enter the date in the type=date field in html page.
I want to restrict the user to select the date only from the calender display which is MM/DD/YYYY.
Below is the code in html page :
<input type="date" name="bankTrans" ng-model="orderAstro.paymentDate"
class="form-control" id="bankTrans"
ng-disabled="isDisabled" required />
Also attaching the image for error clarity :
Image for error clarity
use following line of code to restrict manual date field entry using jquery.
$("input[type='date']").keydown(function (event) { event.preventDefault(); });
Edit 1:
Your question makes sense.
The best way to work with a date is to disable manual entry and allow changes only using the Date Picker.
Add a 'readonly' attribute to the input field:
<input type="date" readonly name="bankTrans"
ng-model="orderAstro.paymentDate" class="form-control"
id="bankTrans" ng-disabled="isDisabled" required />
Do you want the code for above Angular js file and HTML as well or this much is fine.
Edit 2:
Disabling the manual Entry of Date and allowing only through Date Picker.
HTML code:
<input type="text" readonly class="form-control" datepicker-popup="{{clCtrl.format}}"
ng-model="clCtrl.QualityExpirationDate" is-open="clCtrl.openedQualityDate"
min-date="clCtrl.minDate" datepicker-options="clCtrl.dateOptions"
ng-required="true" close-on-date-selection="true"
show-button-bar="false" />
js file:
$scope.$watch('dt', function(val) {
$scope.isValidDate = isNaN(new Date(val).getTime());
});
self.dateOptions = {
formatYear: 'yy',
startingDay: 1
};
self.formats = ['MM-dd-yyyy', 'MM/dd/yyyy', 'MM.dd.yyyy', 'shortDate'];
self.format = self.formats[0];
self.openQualityDate = function ($event) {
$event.preventDefault();
$event.stopPropagation();
self.openedQualityDate = true;
};
self.toggleMin = function () {
self.minDate = self.minDate ? null : new Date();
};
self.toggleMin();
self.clear = function () {
self.QualityExpirationDate = null;
};
Please ignore this, is not solving the issue, as intended.
This might help: https://jsdaddy.github.io/ngx-mask-page/main#prefix
<input mask="00/00/0000">
what worked for me!
added the following attributes to my date type input tags.
<input type="date" name="dob" "minlength": "10", "maxlength": "10", class="form-control" />
I don't know Javascript at all. I have a form where there can be any number of datepicker textboxes. When the user selects a date in the first datepicker textbox, then I want all the remaining datepicker textboxes to have that same date.
Does this require a function?
Edit: I tried to create a function, but I don't know javascript at all!
function UpdateValuationDates(event) {
$valuationDatePicker = $(event.target);
var valuationDate = $valuationDatePicker.datepicker("getDate");
if (valuationDate != null) {
//loop through all items
document.getElementById("dateValuationDate").Text
$valuationDatePicker.datepicker("setDate", valuationDate);
$valuationDatePicker.trigger('change');
}
}
So I think this can be ignored. I have also read that there is a datepicker on selected event:
$(".date").datepicker({
onSelect: function(dateText) {
display("Selected date: " + dateText + "; input's current value: " + this.value);
}
});
So I guess I need to edit this code to populate the rest of the textboxes, but how to find out at runtime how many there are?
The HMTL has a repeater with the datepicker repeated x number of times:
<abc:DatePicker runat="server" ID="dateValuationDate"
With the help of html's input type=date and some basic classes' knowledge, you can do that.. Considering you have following Date pickers:
<input type="date" class="dateTime">
<input type="date" class="dateTime">
<input type="date" class="dateTime">
Now you simply need to listen to a change in any one of there values:
$(".dateTime").on("change", function(){
and when the change occurs, get the changed value and set all other date pickers to that new value:
$(".dateTime").val($(this).val());
So it'll be something like this:
$(document).ready(function(){
$(".dateTime").on("change", function(){
$(".dateTime").val($(this).val());
});
});
See the DEMO here
EDIT: Considering you're new to JavaScript, here's how i'm getting the reference to all those elements, through .className, as they all have same class name so for each event (change, update value) they all will be referenced.
I would like to have a function that checks if a date in a field is more than 50 years in the past from todays date. If the date is more than 50 years in the past, a message should be shown, but there should not be any minimum date (maximum years).
I have a form where it is possible to add more fields dynamically (name + birthdate), and every new "form" should show this message under the birthday field if it is more than 50 years in the past.
The warning message under each birthdate field should be something like this (if over 50):
<div class="alert alert-warning">This person is over 50 year. Remember to do...</div>
My html setup:
<label for="id_nested-0-name">Name</label>
<input id="id_nested-0-name" maxlength="200" name="nested-0-name" type="text" />
<label for="id_nested-0-birthdate">Birthdate</label>
<input class="dateinput" datadatepicker="datepicker" id="id_nested-0-birthdate" name="nested-0-birthdate" type="date" />
<!-- If nested-0-birthdate is over 50, add html with warning message -->
<!-- New person -->
<label for="id_nested-1-name">Name</label>
<input id="id_nested-1-name" maxlength="200" name="nested-1-name" type="text" />
<label for="id_nested-1-birthdate">Birthdate</label>
<input class="dateinput" datadatepicker="datepicker" id="id_nested-1-birthdate" name="nested-1-birthdate" type="date" />
<!-- If nested-1-birthdate is over 50, add html with warning message -->
Edit:
This code works great in chrome, but does not work in safari. Anyone see what could be wrong?
<script type="text/javascript">
$(document).ready(function() {
$(function(){
$("#collapse1 input.dateinput").on("change.dp change keyup paste click propertychange",function (e){
var timediff1 = moment().diff(moment($(this).val()), 'years');
if (timediff1 >= 50 ) {
$('#alert1').remove();
$('#collapse1 .panel-body').append('<div id="alert1">Over 50!</div>');
} else {
$('#alert1').remove();
}
});
});
});
</script>
Using http://eonasdan.github.io/bootstrap-datetimepicker/ for my date picker.
Edit 2:
I was missing data-format="DD/MM/YYYY" on my input. Now everything works!
If you dont mind using moment.js
JSFiddle with demo
boolean isOldGeezer = moment().diff(moment($(this).val()), 'years') > 50;
Three part answer to this question
First you need to get the date 50 years ago. I am using a small hack here. You can find better techniques in StackOverflow.
ago50y = new Date();
ago50y.setFullYear(ago50y.getUTCFullYear()-50);
Second, compare that date when the input changes. The following code uses jQuery.
$('input.dateinput').change(function (event) {
if ($(event.target).val() < ago50y.toJSON().slice(0,10)) {
$('#alert').text('This person is over 50 year. Remember to do...');
} else {
$('#alert').text('');
}
});
Third, invoke the second part whenever you add a new set of inputs. Put the above code in a function and include that in the callback while adding the new set.
http://jsfiddle.net/FA4hJ/
i am using two separate timepickers to compute a time duration which works out well for the user. however, i also want to have access to the duration -- which I would like to use in a calculation late on the page. my question is -- how can i access the duration which has already been computed and is displayed to the user upon use of the second timepicker?
I am using this jquery timepicker: https://github.com/jonthornton/jquery-timepicker#timepicker-plugin-for-jquery
my html
<div class = "form-group">
<label for="lesson_start_time">Lesson start time:</label>
<input type="text" id="lesson_start_time" name="lesson_start_time" class="form-control ui-timepicker-input">
</div>
<div class = "form-group" id="end_time">
<label for="lesson_end_time">Lesson end time:</label>
<input type="text" id="lesson_end_time" name="lesson_end_time" class="form-control ui-timepicker-duration">
</div>
my js
// for start time of lesson
$('#lesson_start_time').timepicker({ 'step': 15 });
// temporarily disable end time
$("#lesson_end_time").prop('disabled', true);
// when a start time is chosen
$('#lesson_start_time').on('changeTime', function() {
// enable the end time input
$('#lesson_end_time').prop('disabled', false);
// enable the input as a timepicker
$('#lesson_end_time').timepicker({
'minTime': $(this).val(),
'showDuration': true,
'step':15
});
});
Unfortunately, this plugin doesn't provide requested functionality. You can post a feature request at Github for it.
But there is a workaround: you can use actual value of the selected duration by finding appropriate span and get it's text().
HTML that is generated for timepicker is:
<div class="ui-timepicker-wrapper ui-timepicker-with-duration">
<ul class="ui-timepicker-list">
<li>12:15am<span class="ui-timepicker-duration"> (15 mins)</span></li>
<li class="ui-timepicker-selected">1:00am<span class="ui-timepicker-duration"> (1 hr)</span></li>
<!-- ... -->
</ul>
</div>
We can use it in following way:
When creating timepicker for lesson_end_time, add className:
'endTime' option:
$('#lesson_end_time').timepicker({
/*...*/
className: 'endTime'
/*...*/ });
This class will be added to the topmost div, so, it will become:
<div class="ui-timepicker-wrapper endTime
ui-timepicker-with-duration">
Inside changeTime handler find needed span in this way:
var selectedDurationSpan = $(".ui-timepicker-wrapper.endTime").find("li.ui-timepicker-selected").find("span.ui-timepicker-duration");
Then we can get it's value. It will be in parenteses and with spaces (" (30 mins)"), we can purify it ro become "30 mins":
var selectedDuration = selectedDurationSpan.text().trim().replace(/[()]/g,'');
Value could be applied to some input, (i have created <input id='lesson_duration' />):
$("#lesson_duration").val(selectedDuration);
So, here is full code for lesson_end_time timepicker initialization:
$('#lesson_end_time').timepicker({
minTime: $(this).val(),
showDuration: true,
step: 15,
className: 'endTime'
}).on("changeTime", function () {
var selectedDurationSpan = $(".ui-timepicker-wrapper.endTime").find("li.ui-timepicker-selected").find("span.ui-timepicker-duration");
var selectedDuration = selectedDurationSpan.text().replace(/[()]/g, '');
$("#lesson_duration").val(selectedDuration);
});
Full demo is HERE
it can be computed this way:
http://jsfiddle.net/4fqU8/1/
$(function(){
$('input.time').timepicker();
$('#delta').on('click', function(){
var seconds = $('#time2').timepicker('getSecondsFromMidnight') - $('#time1').timepicker('getSecondsFromMidnight');
// compensate for negative values;
if (seconds < 0) {
seconds += 86400;
}
alert((seconds / 60) + ' minutes');
});
});
from:
https://github.com/jonthornton/jquery-timepicker/issues/191