Javascript - loop through datepickers and set date - javascript

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.

Related

Bootstrap Datepicker With Daterange Not Saving Value as the Specified Format

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.

ng-model doesn't update value when using JQuery datepicker

So I have two textboxes for the user to select a date and I am using JqQuery's datepicker UI to display a small calendar popup when the textbox is clicked. Now the problem is that when I click on the textbox, the calendar pops up, I select a date and then the textbox gets filled with that date and my scope variable in javascript also gets updated. However, in my HTML, the value of "From" date box doesn't get printed until I click on "To" date box. Below is my code:
home.html
<form name="myForm">
From Date:
<input type="text" id="dateFrom" ng-model="data.dateFromChosen" />
To Date:
<input type="text" id="dateTo" ng-model="data.dateToChosen" />
</form>
<p>You chose: {{ data.dateFromChosen }} and {{ data.dateToChosen }}</p>
script.js
$scope.data = {};
$("#dateFrom").datepicker({
onSelect: function(dateText) {
$scope.data.dateFromChosen = $("#dateFrom").datepicker({dateFormat: 'mm/dd/yyyy'}).val();
alert("You chose " + $scope.data.dateFromChosen);
}
});
$("#dateTo").datepicker({
onSelect: function(dateText) {
$scope.data.dateToChosen = $("#dateTo").datepicker({dateFormat: 'mm/dd/yyyy'}).val();
alert("You chose " + $scope.data.dateToChosen);
}
});
So this is what happens: I click on from date box and select a date. Then I get the popup saying that You chose 06/01/2016 which means the $scope.data.dateFromChosen = 06/01/2016. But it doesn't get displayed in my HTML. Then when I click on to date box, the value of dateFromChosen gets printed on HTML. Does anyone know why this happens and how to fix it? Thanks
Try adding $scope.$apply() to force angular to rerun digest cycle.
$scope.data = {};
$("#dateFrom").datepicker({
onSelect: function(dateText) {
$scope.data.dateFromChosen = $("#dateFrom").datepicker({dateFormat: 'mm/dd/yyyy'}).val();
$scope.$apply();
alert("You chose " + $scope.data.dateFromChosen);
}
});
$("#dateTo").datepicker({
onSelect: function(dateText) {
$scope.data.dateToChosen = $("#dateTo").datepicker({dateFormat: 'mm/dd/yyyy'}).val();
$scope.$apply();
alert("You chose " + $scope.data.dateToChosen);
}
});

jquery filter comparing dates

I'm currently trying to create a filter that will allow me to select a date using jQueryUI datepicker. This date will then be compared to the value of a hidden input. The parent div of the hidden input will then be hidden using .hide() function if the hidden date is less than the date select using the picker.
<div data-value="I0001-APP0277-S" class="server_wrapper" style="display: block;">
<div class="detail_wrapper">....</div>
<input type="hidden" class="buildStart_hidden" value="4/25/2014 1:46:19 pm">
</div>
<input type="text" id="buildStart_filter" class="secondary_live_filter hasDatepicker">
Using this code:
$('#buildStart_filter').change(function(){
var date = $(this).val();
$('.buildStart_hidden').each(function(){
if(date>$(this).val().split(' ')[0]){
$(this).parent().hide();
}
});
});
But using this code doesn't work. I think it may be due to the comparison of string values rather than date values. What can I change to make the comparison work?
Maybe:
You missing to remove the hour from DATE
date.split(' ')[0] > $(this).val().split(' ')[0]
After some more work I have figured out the problem.
I was trying to compare string types and not Date types.
This code is working now as hiddenDate and FilterDate are Date() types and thus can be evaluated using >= operator:
$('#buildStart_filter').change(function(){
var filterDate = $('#buildStart_filter').datepicker('getDate');
$('.buildStart_hidden').each(function(){
var hiddenDateStr = $(this).val();
var hiddenDate = new Date(hiddenDateStr);
if(filterDate>=hiddenDate){
$(this).parent().hide();
}else{
$(this).parent().show();
}
});
});

Allow access to computed duration in jquery time picker

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

textbox access for datepicker

I'm using a date picker jQuery plugin created by Stefan Petre and available here:
http://www.eyecon.ro/datepicker/#about
This is a code I'm using to apply datepicker to textboxes
$('.tableMstCellECD').DatePicker({
format: 'd/m/Y',
date: $('.tableMstCellECD').val(),
current: $('.tableMstCellECD').val(),
calendars: 3,
onChange: function (formated, dates) {
$('.tableMstCellECD').val(formated);
$('.tableMstCellECD').DatePickerHide();
}
});
It works fine, but obviously updates values of all textboxes instead of selected one. The problem is that there can be different number of texboxes so I cannot hard code access values. I was trying to implement "this" keyword somewhere into this command but did not succeed
I agree with Deepanshu, you should use jQuery UI. If you want to avoid that for some reason, KarelG's solution works just fine, however since you already include jQuery, you can write it like that:
$('.tableMstCellECD').each(function(){
var id = $(this).attr('id');
$(this).DatePicker({
format: 'd/m/Y',
date: $('#' + id).val(),
current: $('#' + id).val(),
calendars: 1,
onChange: function (formated, dates) {
$('#' + id).val(formated);
$('#' + id).DatePickerHide();
}
});
});
You also have to generate unique ID-s for the input elements either on the server or the client side, like this:
<input type="text" id="01" class="tableMstCellECD" />
<input type="text" id="02" class="tableMstCellECD" />
<input type="text" id="03" class="tableMstCellECD" />
<input type="text" id="04" class="tableMstCellECD" />
i also have this problem before. So i wrote an own script (in js) to implement it to textboxes which contains only the class name "datepicker" or something different. To provide support to most browser, i have done it by this way ;
/*
* === javascript file to implement datepicker on form fields for dates
*
* #author : Karel Geiregat
* #version : 1.0.4 - 18 may 2013
*/
// class name which contains input box, chosen for dates
var comparerString = "datepicker";
// get all inputfields, select only those marked with right class name
window.addEventListener('load', function() {
// select all input boxes
var getElements = document.getElementsByTagName("input");
// check count
var count = getElements.length;
// loop through elements
for(var i = 0; i < count; i++) {
// get classname - supported by most major browsers
if (getElements[i].className == comparerString) {
var idField = "#" + getElements[i].id;
$(idField).datepicker({ dateFormat: "yy-mm-dd" });
}
}
});
and in HTML
<input id="form_startDate" class="datepicker" type="text" required="required">
Just write something similar in jQuery. Just add a class name to the textbox which should be tagged with the DatePicker object.

Categories

Resources