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
Related
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>
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'});
});
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.
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">
I am using this calendar: http://javascriptcalendar.org/
to pick a specific day. It works fine. I want when the user selects a day from the calendar to display a message in a div which will also contain this day. However, even though I have tried the Javascript and jQuery events: onclick, onchange, select, keyup I can't make it work. These events work only if after picking the day I press with my keyboard a char.
Can you help me please?
Here's an example from the plugin's website.
g_calendarObject.setOnSelectedDelegate(function(){
var obj = g_calendarObject.getSelectedDay();
alert("a date was just selected and the date is : " + obj.day + "/" + obj.month + "/" + obj.year);
});
I'm sure you've probably already seen that though, maybe you can make a jsfiddle and I can probably help a little better then.
try this code
<input type="text" id="dt">
<div id="showdate" style="display:none">
</div>
<script>
$("#dt").change(function() {
$("#showdate").css("display", "block");
var txt=$(this).val();
$('#showdate').text(txt);
});
</script>