Dynamically setting date and time in DateBox Jquery Mobile - javascript

I need to populate date and time dynamically to JQuery DataBox input field. I teried to do but it is populating the current date in the input fields irrespective of the data I pass.
Here is the date picker which I am cloning to dynamically have in my interface.
Html:-
<input class="time-input day-time-picker day-time-picker-inline-input" type="text" data-role="datebox" data-options='{"mode":"datebox", "useFocus": true}' style="width:8em" />
Javascript:-
var datePicker = $("#date-time-picker-template-container .date-time-picker-template").clone();
Similar way I created a time picker and cloned as did above,
Html :-
var timePicker = $("#time-picker-template-container .time-picker-template").clone();
Javascript :-
<input class="time-input day-time-picker day-time-picker-inline-input" type="text" data-role="datebox" data-options='{"mode":"timebox", "useFocus": true}' />
Inserting Date
$(".time-input", datePicker).datebox();
$(".time-input", datePicker).datebox("refresh");
$(".time-input", datePicker).datebox('setTheDate', dynamicDate);
Inserting Time
$(".time-input", dayTimePicker).datebox();
$(".time-input", dayTimePicker).datebox("refresh");
$(".time-input", dayTimePicker).val('datebox', {'method':'set', 'value':dynamicTime});
I want to set date and time to these DateBox input fields dynamically based on the response I get.
Is there any control to get date and time in a single control using DateBox ?
Thanks.

Clone your templates, add them to a container DOM element and then tell the element to enhanceWithin(). This creates the databox widgets, then set the date and time using the setTheDate method:
$("#btnAdd").on("click", function(){
var dynamicDate = new Date(2014,3,22,10,11,0,0);
var datePicker = $("#templates .date-time-picker-template").clone();
var dayTimePicker = $("#templates .time-picker-template").clone();
$("#time-picker-block").append(datePicker).append(dayTimePicker).enhanceWithin();
$(".date-input", datePicker).datebox('setTheDate', dynamicDate);
$(".time-input", dayTimePicker).datebox('setTheDate', dynamicDate);
});
DEMO

I'm not sure I follow what it is you are trying to accomplish, but yes, there is a mode that allows both date and time operation at the same time - slidebox.
You will need to set (at least) the following options:
{
mode = "slidebox",
overrideSlideFieldOrder = ["y","m","d","h","i"],
overrideDateFormat = "%Y-%m-%d %k:%M
}
For what it's worth, flipbox could probably be altered to work with both, but it's non-trivial. datebox can likely already work (I've never tried), but you'll need to pretty heavily alter the CSS - at least making the control a good deal wider first.

Related

Trouble sending JavaScript into <input type="date"> calendar

Goal: Attempting to automate a calendar on Chrome using Selenium(Python + behave).
The issue: The date is only being set when actually clicked through the calendar. Passing a value via JavaScript is not working.
Note: According to docs the inputs should allow users to send input in with keys by default but that doesn't even work. It does not accept keyboard input at all.
Problem Walkthrough
This is the original input fields. The div class they are contained in is inside a #shadow-root
(open):
Ignoring the Python. I will try and change the values with some simple JavaScript in the Chrome Dev Tools console:
x = document.querySelector("#class > something").shadowRoot.querySelector("div > div > input[type=date]:nth-child(5)") #Select input for From Date
x = "2022-05-12"
y = document.querySelector("#class > something").shadowRoot.querySelector("div > div > input[type=date]:nth-child(5)") #Select input for To Date
y = "2022-06-12"
After sending in the new values and clicking search. It does not recognize the values as being entered:
However, when manually selected through the calendar:
The dates are accepted and as inputs:
The HTML for the calendar is:
<input type="date" min="2022-01-01" max="2022-07-19">
Clearly. The JavaScript alone does not seem to be enough. If you use the same method above on this calendar it will work. However, on the calendar I am attempting this JS method will not work for some reason. Also, I cannot get Selenium to click and open the calendar on its own for some odd reason.
Solution: Manually trigger the event (Source)
let element = document.getElementById(id);
element.dispatchEvent(new Event("change")); // or whatever the event type might be
dispatchEvent() Documentatio
Event() Documentation

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 .

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 to make the materialize date picker (in fact pickadate) editable?

I'm trying to make the materialize date picker editable. Here is the goal, the user can directly write the date in the input field or use the widget to pick a date.
I did something that is about to work on this jsfiddle. But there is a bug I'm trying to solve. When the user directly writes the date in the input, the picker needs to get the new value also (because I use a different format to submit the date and there is a an hidden input field to update). To accomplish that I tried to do
picker.set('select', $(this.val());
But it creates an infinite loop because the method set in materialize also triggers the event change on the input.
EDIT: oh i just found there is an issue open about that on github. Do you have any idea for a workaround?
Any specific reason you want to do it in the change method?
Why not something like this?
this.change(function(event) {
});
this.bind('blur keypress',function(e){
if (moment($(this).val(), "DD/MM/YYYY", true).isValid()) {
var inputFieldDate=getFmtDate($(this).val());
picker.set('select',inputFieldDate);
}
});
This is a utility function to parse the date in DD/MM/YYY format and get a javascript Date object
function getFmtDate(s){
var valx=new Array();
if(s!=null && s.length>0){
valx = s.split('/');
}
var d = new Date(valx[2],valx[1]-1,valx[0]);
return d;
}
This works for me.
Update:
Once you attach a widget to an html element, the usual event callback functions do not work the way you expect them to. Their functionality is overridden by the widget. You cannot use the functions the same way you are used to and have to find a workaround. In short you cannot use the change function to set or unset the date because set triggrers a change event.
In your case you want to address multiple issues which are very common problems. You should be able to get a lot of examples online to achieve each one of those. What I've done is just one way of doing it.
Populate the form in a non traditional way when the page loads.
Initialize various plugins with values from the form when the page loads
Initialize content from hidden fields when the form loads and update the hidden fields when submitting the form.
Fetch the values by name (of the hidden fields) and use them to initialize the widgets.
I've used blur keypress just to give you an idea that all your requirements can be handled without using change. You use the events that work for you. You can set the date by binding picker to calendar object with this keyword and access it from its instance as shown below.
(function($) {
$.fn.calendar = function(options) {
// Options du datepicker
var settings = $.extend({
editable: true,
format: 'dd/mm/yyyy',
formatSubmit: 'ddmmyyyy'
},
options
);
this.pickadate(settings);
//var picker = this.pickadate(''); will not work
this.picker = this.pickadate('picker');
this.change(function(event) {
});
this.bind('blur keypress',function(e){
if (moment($(this).val(), "DD/MM/YYYY", true).isValid()) {
var inputFieldDate=getFmtDate($(this).val());
picker.set('select',inputFieldDate);
}
});
var $triggerIcon = $('<div class="col s2 center-align"><a class="btn-floating btn-large waves-effect waves-light trigger-datepicker">Date</a></div>');
$triggerIcon.click(function(event) {
event.stopPropagation();
event.preventDefault();
picker.open();
});
this.parent().after($triggerIcon);
// Resolves picker opening for thing
this.next().unbind("focus.toOpen");
return this;
};
}(jQuery));
To set a date:
//This is how you set a date
var cal = $('.datepicker').calendar();
//You can access picker because we changed
//var picker to
//this.picker above in fn.calendar
cal.picker.set('select', getFmtDate($("[name=hiddenDate]").val()));
// The syntax is
//cal.picker.set('select', new Date());
$('#formulaireDate').validate();
You have to convert your date to Date(). The below function should give you an idea. You can also use plugins like jquery dateFormat plugin.
function getFmtDate(s){
var valx=new Array();
if(s!=null && s.length>0){
valx = s.split('/');
}
var d = new Date(valx[2],valx[1]-1,valx[0]);
return d;
}
This is your html.
<div class="row">
<div class="col s4">
<input type="text" class="datepicker" />
<input name="hiddenDate" type="hidden" value="12/12/2016">
</div>
</div>

protractor unable to set the ng-model value

Im using materialize css for the date-picker and using protractor to test it as shown in
http://plnkr.co/edit/pSskRfOy3f1NKo6KYgWD?p=preview
When i tried to element(by.model('newPatReports.reportDate')).sendKeys('14 January, 2016'); Im unable to set value instead open up the date-picker- this happens on firefox only
But in chrome it says cannot focus element...What could be the possible way to bind with my model
I also tried to remove the custom attribute, but i didnot succeed
Any help is appriciated.......Thanks in advance
The idea is to remove the readonly attribute from the date input element, click it to trigger the date picker, hide the date picker and send keys to the input:
var EC = protractor.ExpectedConditions,
rptdate = element(by.name("rptdate"));
browser.wait(EC.visibilityOf(rptdate), 15000);
// remove the "readonly" attribute
browser.executeScript("arguments[0].removeAttribute('readonly');", rptdate.getWebElement());
// trigger the date picker
rptdate.click();
// hide the date picker
browser.executeScript("arguments[0].style.visibility = 'hidden';", $('.picker').getWebElement()).then(function () {
rptdate.sendKeys('14-12-2015');
});
Works for me.

Categories

Resources