bootstrap datepicker and local storage - javascript

I would like the user to select a date from a bootstrap datepicker component and store the selected value in local storage. When the user has completed their selection they can select the button whereupon an ajax call will use the local storage.
At this moment I'm having trouble getting the datepicker component to set a value in the local storage. The date picker component renders when the user selects is and the user's selection becomes the value of the input field.
Here is the mark up:
<form>
<div class="form-group">
<label for="edge-name" class"control-label">Start:</label>
<input type="text" class="form-control" id="filterStart">
</div>
</form>
And the javascript
$(document).ready(function(){
$('#filterStart').datepicker();
$('#filterStart').on('changeDate' function(){
var newValue = $('#filterStart').datepicker('getFormattedDate')
localStorage.setItem('filterStart',newValue);
});
I've inserted console.log in various places throughout the javascript but the code never writes to the console therefore I know that its not writing to the local storage. I know that the local storage is working because I'm using it other parts of the code.
Also, any suggestions on how to do this better would be greatly appreciated.

If you are using this bootstrap-datepicker you can take a look to the following jsfiddle:
$('#filterStart').datepicker();
$('#filterStart').on('changeDate', function (e) {
var newValue = $('#filterStart').datepicker('getFormattedDate')
localStorage.setItem('filterStart', newValue);
});
$('#btn').on('click', function(e) {
$('#logMsg').val('Value saved in local storage is: ' +
localStorage.getItem('filterStart'));
})

I can't find if method 'getFormattedDate' exists but there is a standard getDate method for that. By the way you miss a semicolon in definition line of newValue;

I think you might be instantiating a new datepicker in your changeDate event. You could try getting the formatted date from the .data:
var newValue = $('#filterStart').data('datepicker').getFormattedDate('yyyy-mm-dd');

Related

display the input values even after the results are shown

I have an html page, which has two fields From date and To date. On clicking the submit button I'm able to retrieve the information based on the dates and display it,in the same page but my From date and TO date fields become empty. So how do I hold the values so that they are retained in their respective fields even after the displaying the information.
HTML:
<ion-content ng-init=onViewloaded()>
From:
<input type="date" ng-model="fromDate">
To:
<input type="date" ng-model="toDate">
<button type="submit" ng-click="Save()">Submit</button><br>
Data:
{{receivedData.name}}
{{receivedData.information}}
</ion-content>
Controller:
$scope.receivedData;
$scope.onViewloaded=function()
{
bulkDateService.getData($scope.RetrievedData);
}
$scope.RetrievedData = function(data,error)
{
$scope.receivedData=data;
}
$scope.save=function()
{
var dataToSend={'from':$scope.fromDate, 'to':$scope.toDate};
bulkDateService.postData(dataToSend,error);
}
So what am I missing to do, in-order to display the From date and To date in their fields even after loading the data?
Since you are passing the objects by references in var dataToSend={'from':$scope.fromDate, 'to':$scope.toDate};, probably they are getting deleted or changed inside theis function bulkDateService.postData(dataToSend,error); (when you alter the field 'to' and 'from' of dataToSend.
To try this out, send a copy of the dates instead of the reference and see if that fixes your problem. Like this:
var dataToSend={'from':angular.copy($scope.fromDate), 'to':angular.copy($scope.toDate)};
And try to avoid ng-init directive, keep controller logic away from view whenever you can. For this you can simply call the function on the controller:
$scope.onViewloaded=function()
{
bulkDateService.getData($scope.RetrievedData);
}
$scope.onViewloaded();
Or even better, use ionic's view events: Ionic Docs
$scope.$on("$ionicView.beforeEnter", function(event, data){
$scope.onViewloaded();
});

How do I save a file triggered by button click in CasperJS?

I am trying to download a log that is filled by date range, so I fill out the form with the dates I want and then when you click the "Export Call Logs" button it just automatically triggers a CSV file download in a regular browser.
How do I save that file that should be automatically triggered when 'clicking' the same button using Casper?
casper.then(function(){
console.log("Filling out form and getting CSV");
this.evaluate(function(){
document.getElementsByName("startdate")[0].value="08/30/2016";
document.getElementsByName("enddate")[0].value="08/30/2016";
document.getElementsByName("s1")[0].click();
});
});
The button HTML is as follows:
<td><input type="submit" name="s1" value="Export Call Logs"></td>
Also, as a side note, obviously I don't want to manually input the date, kinda defeats the point of a program in a way, I am most familiar with Pyhon, is their some sort of equivalent to the DateTime module or someway I can use Casper to get the previous days date and store as a Var to input accordingly? i.e todays date is 08/31/2016 I would want to input the previous day, 08/30/2016.
EDIT:
Tried implementing the example commented below.
casper.then(function(){
console.log("Filling out form and getting CSV");
this.page.onFileDownload = function(status){console.log("onFileDownload(' + status + ')");
return "downloadedfile.csv"; };
this.evaluate(function(){
document.getElementsByName("startdate")[0].value="08/30/2016";
document.getElementsByName("enddate")[0].value="08/30/2016";
document.getElementsByName("s1")[0].click();
});
});
You can try download() function, you can find more information here.
There is an example.

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>

jQuery datepicker does not update value properly

On the website I'm currently working I have a form to add a event. This event needs a date which the user selects using a jQuery datepicker. A date can only have one event. So I want to check the date the user insert in the datepicker. I tried doing this by getting the value after the user has selected the date. The problem is however, the datepickers doesn't update his value right away.
I made a JSFiddle to show the problem. When you pick a date the span updates and shows the value of the datepicker. But as you can see the first time it is blank, and the second time it shows the previous selected date. So the datepickers does not update is value right away. How can I fix this?
I looked trough other similar questions here on stackoverflow but their solutions didn't work for me.
JSFiddle: http://jsfiddle.net/kmsfpgdk/
HTML:
<input type="text" id="datepicker" name="date" />
<span id="data"></span>
JS:
$('#datepicker').datepicker();
$('#datepicker').blur(function () {
var val = $(this).val();
$('#data').text(val);
});
Its better to use built in method onSelect:fn to use:
$('#datepicker').datepicker({
onSelect: function () {
$('#data').text(this.value);
}
});
Fiddle
As per documentation:
onSelect
Called when the datepicker is selected. The function receives the selected date as text and the datepicker instance as parameters. this refers to the associated input field.
change event happens before blur event.
Use .change() instead of .blur()
$('#datepicker').change(function() {
var val = $(this).val();
$('#data').text(val);
});
Updated jsFiddle Demo
If Google brought you here because your input does not seem to respond to various JQuery .on( events, most likely it's because you have another element on the same page with the same id.

onchange of javascript filled in field issue

I want to use onchange() event on a text field that may be filled in by a date picker using javascript. i tried to use onblur(), onmouseover() and etc but non of them can help me to catch its value just after changing by date picker.
a part of code that defined date picker and fill in text field is like below:
<script type="text/javascript" src="Scripts/cal_.js"></script>
<input type="text" name="receive_date" id="receive_date" style="width:75px" class="cdate" value="" {{attributes}}>
<script type="text/javascript">
new LCalendar('receive_date');
</script>
but when I want to add onchange="_do_something()" in place of {{attributes}} it does not work.
The text input is don't have change event. the event you can use to get the input change is to use 'input'. see sample
inputVar.addEventListener('input', function(){'what you want to do.'});
This is simplistic, but you could try this:
var val;
document.getElementById('receive_date').addEventListener('focus', function() {
// set the value
val = this.value;
});
document.getElementById('receive_date').addEventListener('blur', function() {
if (this.value !== val) {
// val was changed
} else {
// val was not changed
}
});
Thanks for good answers.
After testing so many solutions i changed my calendar library code.
Just after filling in date (text) field in code:
receive_date_field.value=...;
I tried to put:
a.focus();
a.blur();
twice and for catching its value after every filling in (either by another javascript code) i used:
onfocus="_do_something();"
in place of {{attributes}} !!! as you see this is not what i want but just is a temporary way to catch value of field after every filling in.

Categories

Resources