Datepicker conversion issues - javascript

I'm new to all this and I'm a hard time trying to do what appears to be a simple thing. This is what I'm trying to do. I'm using jquery datapicker to create two dates. A beginning date (beginningdate) and an end date (enddate). I need to use these dates for the following things:
Use the 2 dates in a where statement in a mySQL query.
Calculate the difference between the dates and use them in the same where statement in the mySQL query.
Use the mySQL statement to populate a chart using AMCharts.
Use the same page to draw that chart.
So basically, I'm trying to input the two dates and use those two dates to populate a chart without using two pages to do it. So this is what I have done so far.
Created a php page called mealplanner.php
Created a form on this page and added the two dates fields
After posting, the two dates work in the where statement (number 1 above) using
where m.date >= ('" . $_POST['beginningdate'] . "')
and m.date <= ('" . $_POST['enddate'] . "')
The chart populates on the same mealplanner.php page since I am refreshing the page after post (number 3 and 4).
After or during the posting, I need to calculate the difference between the 2 dates and use that number in a php variable named $diffdate. This is where I run into issues. I can manually hard code a javascript variable
var diffdate = 9;
I can then pass that variable to php during post using
window.location.href = "?p=mealplanner&diffdate=" + diffdate;
and use
$diffdate = $_GET["diffdate"];
in my php section to use the variable in my mySQL statement but I obviously can't use a hard coded variable and need to calculate the two dates. this is my html form
<form id="changedate" action="?p=mealplanner" method="post">
<p>Beginning Date: <br /><input type="text" id="BeginningDate" name="beginningdate"></p>
<br />
<p>End Date: <br /><input type="text" id="EndDate" name="enddate"></p>
<br />
<input type="submit" value="Change Dates" onclick="calcdate();" />
<br />
</form>
and this is how I'm converting the jquery element into a variable
var BeginningDate = document.getElementById("BeginningDate").value;
var EndDate = document.getElementById("EndDate").value;
The problem is that the date is now a string and I can't seem to convert it to a date. I would think that using
var newdate = new Date('BeginningDate');
Would work but it doesn't, I even tried double quoting it. I have tried this:
var dateArr=BeginningDate.split("/");
var date=new BeginningDate( parseInt(dateArr[0], 10),
parseInt(dateArr[1], 10)-1,
parseInt(dateArr[2], 10),
parseInt(dateArr[3], 10);
alert(date);
It simply doesn't see the sting as a date. I also create and display default fields using today as the beginning date and today +7 and the end date. Of course, if I change the dates, the post refresh puts the default back so I need a way to keep the new dates displaying on the after post page. I would assume a issset will be the way to do it but I haven't tried it yet and am looking for suggestions on how to do that as welll. I hope this makes sense and thanks in advance. Here is my datepicker functions if you need that as well.
$(function() {
$( "#BeginningDate" ).datepicker();
$( "#BeginningDate" ).datepicker("setDate", new Date());
$( "#BeginningDate" ).datepicker('option', {dateFormat: 'yy/mm/d'});
});
$(function() {
$( "#EndDate" ).datepicker();
$( "#EndDate" ).datepicker("setDate", "+7");
$( "#EndDate" ).datepicker('option', {dateFormat: 'yy/mm/d'});
});

Related

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 .

Dynamically setting date and time in DateBox Jquery Mobile

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.

How do you prevent bootstrap-datepicker from clearing existing value from input if no date is selected?

I have have a div with a user's date of birth pre-populated with php:
<div id="datepicker" class="input-group date">
<label for="dob">Date of Birth</label> <input type="text" class="form-control" id="dob" name="dob" value="<?php $date = new DateTime($this->swimmers->dob); echo $date->format('d/m/Y');?>"><span class="input-group-addon"><i class="glyphicon glyphicon-th"></i></span>
</div>
The javascript:
<script>
$('.container .input-group.date').datepicker({
startDate: "01/01/1900",
endDate: "01/01/2100",
format: "dd/mm/yyyy",
autoclose: true,
todayHighlight: true
});
</script>
Bootstrap is setup and working correctly however, when the "dob" input gets and loses focus without making a date selection it clears the value that was pre-populated.
This however doesn't happen if a date has been selected via the datepicker and then the input gets and loses focus.
How can the pre-populated value be kept in the field if someone clicks in it?
Edit: The first time you make a date selection, it clears the pre-populated value but doesn't insert the selected date until you make a date selection a second time.
Update: Working code updated!
Set Force parse value to false:
forceParse: false
$(".applyDatepicker").datepicker({
forceParse: false
});
I am not sure about its working in php but for mvc I got the same problem that Bootstrap would erase the value if the control gets and loses focus without making a date selection.
I found that Bootstrap erases the value as it doesn't recognize the value set by
$('#dtControl').val(nextMonth);
I am working with bootstrap v3.1.1 and the following code worked for me
$('#dtControl').datepicker('setDate', nextMonth);
to populate the datepicker control. This way Bootstrap recognizes the date and doesn't erase it if control gets and loses focus
Can't tell for sure without more of an example but the problem is probably that the $this->swimmers->dob string you are giving to the input is not recognised as a date format by bootstrap-datepicker. You can define the date format it uses by adding the data-date-format attribute to your input.
For example if you were using a MySQL formatted date or PHP's DateTime object with $date->format('Y-m-d') you could use:
<div id="datepicker" class="input-group date">
<input type="text" class="form-control" id="dob" name="dob" value="<?php echo $this->swimmers->dob;?>" data-date-format="yy-mm-dd"><span class="input-group-addon"><i class="glyphicon glyphicon-th"></i></span>
</div>
I had a similar problem when a user clicked on the same date twice. The field would "toggle" between the date clicked on and a blank field. I basically didn't want it to be empty at any stage, so here's how I got around that, partly thanks to Waqas's answer:
var datepickerContainer = $('#datepicker');
datepickerContainer.datepicker({
startDate: "01/01/1900",
endDate: "01/01/2100",
format: "dd/mm/yyyy",
autoclose: true,
todayHighlight: true
}).on('show', function() {
datepickerContainer.datepicker.currentDate = $('input#dob').val(); //update this instance with the current value
}).on('changeDate', function(event) {
var newDate = $('input#dob').val();
if (newDate == '' || newDate == null) { //check if the new value is empty - if it is, then just set it back to the last known date for this instance
datepickerContainer.datepicker('setDate', datepickerContainer.datepicker.currentDate);
}
});
That keeps it relatively self-contained, by storing the last date value in that instance of the datepicker and results in no clearing of the input.
I know you solved this problem, but I figured this snippet might come in handy for someone else in a similar situation.
When jQuery calls a handler, the this keyword is a reference to the element where the event is being delivered. Futhermore, a non empty string will evaluate to true. Based on these facts, simply do a check in the event handler. See sample code below.
.find( 'input[name=startDate]' )
.datepicker( {format: 'dd-mm-yyyy'} )
.on( 'changeDate', function() {
if( this.value ) {
<< do something >>
}
});
NOTE: For efficiency and readability in code sample above, the DOM property value is checked, instead of wrapping this in a jQuery object and calling val() on it ( $( this ).val() ). This is a minor improvement, but it's a good practice to be as compact/simple as possible.
Another solution is to define the options at the global level:
$('.datepicker').datepicker();
$.fn.datepicker.defaults.format = 'dd/mm/yyyy';
$.fn.datepicker.defaults.startDate = "0";
$.fn.datepicker.defaults.language = "es";
$.fn.datepicker.defaults.autoclose = true;
$.fn.datepicker.defaults.todayHighlight = true;
$.fn.datepicker.defaults.todayBtn = true;
$.fn.datepicker.defaults.weekStart = 1;
Now, when use update method, datepicker don't lost options.
$('#dob').datepicker('update', '2011-03-05');
You can use like this. Although for me it was working by simply passing value to element by using .val() function.
Reference URL.
https://bootstrap-datepicker.readthedocs.io/en/latest/methods.html

bootstrap-datepicker.js and jquery.maskedinput.js don't play nice

I have to use bootstrap-datepicker.js for my project but it doesn't work well with mask.
problem 1:
It you you are tabbing through fields it will auto populate the date field with today's date. Ideally it won't populate it at all.
Problem 2:
It's difficult to blank-out a the date field once it's populated.
first name: <input type="text">
birthdate: <input type="text" class="date">
city: <input type="text">
js:
$(function() {
$(".date").mask("99/99/9999");
$('.date').datepicker({
format: 'mm/dd/yyyy'
});
});
The problem is all originates from the fact that mask is populating the field with example format characters( "_ _ / _ _ / _ _ _ _" ) during focus and when the focus leaves datepicker is attempting to parse the example characters BEFORE mask has a chance to remove them. datepicker can't parse these special characters into a date therefore it is selecting today's date.
I think that if I can figure out a way to remove the example characters before bootstrap-datepicker attempts to parse them my problem would be fixed.
I would provide a jsfiddler example but I can't figure out how to add bootstrap-datepicker.js and jquery.maskedinput.js on their site.
Thanks for your help.
I stumbles across this option:
$('.date').datepicker({
format: 'mm/dd/yyyy',
forceParse: false
});
Surprising that force parse is true by default. darn bootstrap. Problem fixed.
Late answer but this was the only one that worked for me after deconstructing the sequence of events handled by both plugins (as of this date).
var $date = $('.date');
$date.datepicker({
format: 'mm/dd/yyyy'
});
$date.mask("99/99/9999");
$date.on('keyup', function(){
if ($date.val() == '__/__/____'){
// this only happens when a key is released and no valid value is in the field. Eg. when tabbing into the field, we'll make sure the datepicker plugin does not get '__/__/____' as a date value
$date.val('');
}
});
Long Explanation
Turns out that the datepicker plugin calls an update function on keyup, which in this case is the keyup event triggered when you release the TAB key. This update function calls a DPGlobal.parseDate() function that roughly behaves like this:
DPGlobal.parseDate(''); // returns new Date(); aka. now
DPGlobal.parseDate('10/10/1983'); // returns a Date instance that points to 10/10/1983
DPGlobal.parseDate('__/__/____'); // is generated by the maskedinput plugin and is interpreted as an ilegal date, so the datepicker goes back to the origin of unix time, 1970
This could easily be fixed by changing the parseDate function on the datepicker lib but this is a big no no if you want to keep your code maintainable. We are left then with a hackish way to intercept the foul value and correct it before maskedinput hands it over to the datepicker.
Hope it helps!
Try use other class name to datepicker and mix in your html
$(function() {
$(".date").mask("99/99/9999");
$('.date2').datepicker({
format: 'mm/dd/yyyy'
});
});
birthdate: <input type="text" class="date date2">

Update 2 values when submiting form action

I have a form with several fields. I enjoy all the validation built into a form, and I am forbidden from using ajax.
Here is the issue: My form has a date picker and time selector. But I have to send the values as a combination of them, i.e. 6/7/2013 05:00:00.
From the research I've done, I can't stop and concatenate those values before submitting.
How can I do this without getting involved in too much trickery?
Thanks for any helpful tips!
You can use a hidden element, for this example we'll use this.
<input type="hidden" name="datetime" value=""/>
When the submit event if fired on the form, run this.
$('form').on('submit', function(){
var $form = $(this);
$form.find('[name=datetime]').val(
$form.find('[name=date]').val() + ' ' + $form.find('[name=time]').val()
);
});
EDIT
I just realized this isn't tagged jQuery so here's my best attempt with vanilla javascript assuming the fields name is "add" and there's inputs named datetime, date and time.
var add = document.forms.add;
add.onsubmit = function(e){
add.datetime.value = add.date.value + ' ' + add.time.value;
}
This should definitely be handled on the server side though.
Have a 3rd hidden field, update the value (date + time) on change on either date or time and use that value where ever you want.
you can use jQuery UI Datetimepicker plugin.
its will help you to catch date and time in single field.
plz refer.
$('#selectedDateTimeWithFormat').datetimepicker({ dateFormat: 'dd-mm-yy', timeFormat: 'hh:mm:ss' });
http://timjames.me/jquery-ui-datetimepicker-plugin

Categories

Resources