Pikaday default value is being modified - javascript

I have a field to set date to. This field could have a default value in format YYYYMMDD and it's being transformed to a correct format DD.MM.YYYY, which is understandable for operators. Don't ask me why, it's an ancient system and no, I can't rewrite it since it's using big backends.
I just need to add simple datepicker to those fields. I have chosen Pikaday, which is lightweight and simple enough for this particular task. My typical use-case looks like this:
<input type="text" id="datepicker" value="20150515" customType="date">
<img src="img/icon.gif" id="datepicker-button" />
<link rel="stylesheet" href="css/pikaday.css">
<link rel="stylesheet" href="css/site.css">
<script src="js/moment.min.js"></script>
<script src="js/pikaday.js"></script>
<script>
var picker = new Pikaday(
{
field: document.getElementById('datepicker'),
trigger: document.getElementById('datepicker-button'),
firstDay: 1,
yearRange: [1900,2020],
onSelect: function() {
var date = document.createTextNode(this.getMoment().format('DD.MM.YYYY') + ' ');
document.getElementById('selected').appendChild(date);
}
});
field.parentNode.insertBefore(picker.el, field.nextSibling);
</script>
The original piece of code is the input tag. The rest is my new datepicker functionality.
And now, what's the problem.
The problem is the default value. Let's say that default value is 20151023. The customType attribute should make a correct date of 23.10.2015 but the following Pikaday snippet makes a date of 20.03.1023. I don't know why. I don't understand javascript well but I guess that onSelect param is just a kind of anonymous callback function to be called only in case when user clicks the datepicker button.
Any suggestions, please?
Thanks, JiKra
EDIT:
There seems to be a different problem. If there comes any value from backend, it's in the value format like 20151023. And there is an ancient javascript file with some function, that parses the value and creates a proper format 23.10.2015. Problem is that my Pikaday constructor is being called before that ancient parser. Even when I use promising snippet by jazZRo to modify value before Pikaday call, that ancient parser freaks out because it expects a YYYYMMDD format.
So, what I need is either call my stuff after the ancient parser or prohibit that onSelect callback function in Pikaday constructor to not run on page load.
Is that possible?

Simplest solution is to use momentjs to convert the value of the input before it is being used by Pickaday:
(function() {
var moment = window.moment(document.getElementById('datepicker').value, 'DDMMYYYY');
document.getElementById('datepicker').value = moment.format('YYYY-MM-DD');
})();
See http://jsfiddle.net/05fyr368/3/

Related

show certain date in date picker

I'm using pickmeup datePicker in my Angular project, and it works good and stable but I faced a problem. When I'm trying to set a particular date, picker breaks and/or disappears. I used the method set_date from the documentation but I think I'm missing something.
I use the following code
showDate(timestamp: number) {
const timeString = timestamp.toString();
this.pickerInstance.set_date(new Date(timeString));
}
I have a stackblitz code template here.
So the idea is, I want to have a button when I'm pressing on it, it passes timestamp value to showDate function and after that datePicker shows my date.
I don't want to use jquery here, I believe this could be done without it. But maybe I'm wrong.
Any ideas, comments, help is welcome? thank you.
The constructor of Date needs a number not a a string.
You need to call this.pickerInstance.update() after the update
public showDate(timestamp: number) {
this.pickerInstance.set_date(new Date(timestamp));
this.pickerInstance.update();
}

Change jquery datetimepicker format on event

After much too much googling and searching stackoverflow for my answer, I have been unsuccessful. So I am sorry if this is a duplicate.
I have a datepicker that displays only time. I wish to toggle between military and standard time on a dropdown onchange event.
My attempts have been something of this:
function militarytoggle(element)
{
timetype = $("#military").val();
if(timetype == "military")
{
$('.time').datetimepicker({
timeOnly: true,
timeFormat: 'HH:mm'
});
}
else if(timetype == "standard"){
$('.time').datetimepicker({
timeOnly: true,
timeFormat: 'hh:mm TT'
});
}
}
EDIT: The datetime method I am using (that is currently working) is rendered on document ready:
$('.time').datetimepicker({
timeOnly: true,
dateFormat: '',
timeFormat: 'hh:mm TT'
});
I only wish to change timeFormat on an event.
One would think this would work, redundancy aside. What on Earth am I doing wrong??
Thanks in advance everyone!
One of your if statements is written as
if($(timetype == "military")
the other as
else if(timetype == "standard")
First of all, the former of those has unclosed parenthesis. But also, one uses $ and the other doesn't. Only one of these can be the correct syntax (I'm thinking the later).
Similarly, you use
$('.time').datepicker
in one place and
$('.time').datetimepicker
in the other. Again, only one of these is probably the right method to use.
Edit: added from comments below:
If the datetimepicker method is a constructor, calling it again after the page has been created may not actually change the format of an existing control.
Further:
You should check the documentation (or the source code if there is no good documentation) of the datetime picker widget to see if there is a method for changing the display format of an existing control (or if the format is a public property you might be able to assign it directly). If there is not, then having two versions initialized and hiding one is probably the best way to do it, although you could also do a post back to the server, and have some server side code that uses a passed parameter to render a page with the datetimepicker set to the desired format.
I have solved this problem by adding a military and standard time field for each form. I then toggle the disabled property as well as the display CSS instead of trying to change the datetimepicker.
Then I just bind datetime picker to all fields on document ready.
function militarytoggle(element)
{
timetype = $("#military").val();
if(timetype == "military")
{
$(".standard").prop("disabled",true).css("display","none");
$(".military").prop("disabled",false).css("display","block");
}else if(timetype == "standard"){
$(".standard").prop("disabled",false).css("display","block");
$(".military").prop("disabled",true).css("display","none");
}
}
This seems hacky, if anyone else has a cleaner solution I will accept it as an answer.

Trigger the pattern attribute of input box using javascript?

I need to execute the check for a pattern of an input box using javascript. The reason I need to do this, is because the form gets submitted via ajax every time something is changed in an input box. So this has to be delayed, the check has to be performed, and if incorrect, the ajax process must be stopped. This is all fine, except, how can I trigger the pattern attribute? obviously without using submit.
HTML
<input type="text" pattern="\d{1,2}/\d{1,2}/\d{4}" />
EDIT
I want to be lazy and not re implement the pattern. E.g. I want to get this for free
See in this fiddle
This nice message is contained in the title attribute of the input box and obviously shows so nicely when the user tries to submit something that does not match the pattern.
well someone asked for some reason I don't understand for the ajax snippet. btw handleUTF8Decode.php is solving a charset problem and then including the actual page.
There you go:
$.ajax({
type: "post",
url: "/mycompany/handleUTF8Decode.php",
data: jform.serialize(),
dataType: 'html',
async: true,
beforeSend: function () {
$("#ajax-status").html("Processing");
},
success: function (data) {
},
error: function (xhr, status, error) {
$("#ajax-status").html("ERROR " + "<div class='ajaxResponse'>"+data+"</div>" );
}
});
pattern is nothing to be "triggerd". You just check the validity of the element in question:
jform.find("input[pattern]").prop("validity").patternMismatch // boolean
Updated Answer
In response to the OP's comment below...
I threw this together pretty quick at the end of a long work day, so I apologize for the haggard-ness. A full working example (with extensive notes) can be found on JS Bin. This example shows how you can use jQuery UI's datepicker and tooltip widgets in combination with the input field's standard oninput event to create a dynamic field that does client-side form validation without the need to submit the form data.
I realize that this may not be the most elegant way of doing this, but it is an option that I haven't seen suggested in this forum. Then again, there's probably a good reason for that...
Nevertheless, here's a quick look at the framework -- to see it in 'action', you can check out its JS Bin page. Please excuse the formatting, I'm too lazy for CSS at the moment.
// I've gone ahead and removed most of the code and notes for
// brevity. See: [http://jsbin.com/wuyum/1/edit?js,output]
$(function () {
// Internal function used to incrementally validate the user's
// input (valid for both mm/dd/yyyy & dd/mm/yyyy formats).
function validateInput(contents) {
var rgx = /^(\d{1,2}(?:\/(?:\d{1,2}(?:\/(?:\d{1,4})?)?)?)?)$/;
return rgx.test(contents);
};
// Internal function used to check a valid date format against
// a valid date (e.g. 99/99/2014 is not a valid date).
function checkDate(date) {
return !isNaN(new Date(date).getDate());
};
// Create a new datepicker object and use its onSelect event to
// run through your AJAX call...
$('#date').datepicker({
// onSelect will be called when the user either selects a date
// from the widget, or uses the Return/Enter key on submission.
onSelect: function (date) {
// By now the date has already been validated, client-side,
// in two-part. First the RegEx matched a mm/dd/yyyy format
// and then we confirmed that the date wasn't erroneous with
// checkDate(). If the user submitted an invalid date (say
// '44/44') the widget will automatically reset the date to
// 'today'. Alternatively, you could call checkDate() again
// during this event -- that's really your call.
// Execute your AJAX call
// $.ajax() ...
}
}).tooltip({
// Define a non-delegated tooltip to use as a prompt...
}).on('input', function () {
// Handle the forms RegExp and format validation here...
});
});
It's worth noting that datepicker's default format is mm/dd/yyyy. This can easily be changed, but you should be warned that if your goal is to offer the user the option of entering either mm/dd/yyyy or dd/mm/yyyy, you will run into some issues unless to first validate with format was being used. For example:
10/06/2014 --> October 6th 2014 (mm/dd/yyyy)
10/06/2014 --> June 10th 2014 (dd/mm/yyyy)
Hope this can be of some help to you.
Original Answer
From your RegEx pattern, it looks like your trying to validate the field based on a standard date format mm/dd/yyyy.
If this is the case, and you want to validate the format on every change to the field, I would suggest using jQuery UI and the Datepicker widget -- leveraging the datepickers onSelect event. Like so:
// where #date is the id of <input id="date" type="text"/>
$('#date').datepicker({
onSelect: function(date) {
// $.ajax() here
}
});
Alternatively, you could manage the RegEx validation and AJAX call within the input field's onchange event.
// obviously you'd want to be more specific than simply grabbing the first
// input element found.
document.getElementsByTagName('input')[0].onchange = function (e) { ... };
Lastly, you could look into HTML5 and its implementation of the date type attribute.
Showing an errormessage while the user is still changing the value isn't the best pattern. Simply use an input type="date" and bind to the 'input' event. The input event on this type is only triggered, if there is no type mismatch.
Demo: http://jsfiddle.net/trixta/8e95N/
$(function(){
$('input[type="date"]').on('input', function(){
//your ajax
console.log($.prop(this, 'value'));
});
});

Calculate date difference in jQuery

The question is; there are 2 fields in my application, one is date (Field1) and second is a label (Field2). So, I want that when user selects a date in field 1, then field 2 should be automatically populated (current date - date from field 1).
Can anyone help on how to implement it.
I'm using jQuery to display date:
// This displays the date dialog when user clicks on Field1
$('#Field1').click(function () {
$('#Field1').simpleDatepicker();
});
// Tried following code but it didn't worked
$('#Field1').click(function () {
$('#Field1').simpleDatepicker({
onSelect: function () {
$('#Field2').value(calculateDays($('#Field1').toString))
}
});
});
function calculateDays(dateString) {
var today = new Date();
var inputDate = new Date(dateString);
var days = today - inputDate;
return days;
};
This may look like pathetic code to some folks but I'm just a beginner, so any suggestions/comments are welcome.
Also please tell me if this can be done using html only and no need to go to jQuery. It is my understanding that the calculating days (difference between dates) code will go in jQuery since this needs to be fired after selecting date ('onSelect' event). Please correct if wrong.
I'm assuming that you're trying to use Karl Seguin's jquery.simpleDatePicker (it came top when searching for "simpledatepicker" on Google).
As Jimbo remarks in the comments, it's hard to advise on an MVC approach here — you say you want to do this purely with HTML, but HTML alone can't dictate behaviour (I'd say that's extremely un-MVC). HTML5 forms do allow some limited behavioural control (validation etc), and they also offer <input type="date"/>, but none of these help your situation.
So for this answer I'm just going to fix the mistakes in your code:
The plugin is initialised with the simpleDatePicker jQuery method — you forgot to capitalise the 'P';
The plugin itself caters for the click event. You should initialise it directly without waiting for user input;
There was no onSelect initialisation option in the source code: I chose to use a change event listener on the input to capture this;
You use the jQuery method value — that's native DOM Javascript — you should be using val instead;
toString won't work on DOM elements or jQuery objects — again, use the val method;
The native Date object can't parse dates in arbitrary formats — nor would your code produce a number of days if it did (it would just produce the difference in milliseconds). For this kind of functionality you should use a good date library: I've opted for Moment.
Resulting code (as demonstrated here):
$('#Field1')
.simpleDatePicker()
.on('change', function passValue(){
$('#Field2').val(calculateDaysFromNow($('#Field1').val()))
});
function calculateDaysFromNow(dateString){
return moment.duration(moment(dateString,'MMM DD YYYY').diff()).days();
}
A bit of elaboration on how I've used moment:
First of all, we want to parse #Field1's formatted date for an actual quantifiable date object:
moment(dateString,'MMM DD YYYY')
Next, we want to differentiate that from now. Like Date, moment assumes now if we pass no argument:
moment(dateString,'MMM DD YYYY').diff()
We don't want this as a date, but as a duration, so we'll pass it to moment's duration method:
moment.duration(moment(dateString,'MMM DD YYYY').diff())
…and finally, we want this expressed in days:
moment.duration(moment(dateString,'MMM DD YYYY').diff()).days()
I'm not sure but this:
$('#Field2').value(calculateDays($('#Field1').toString)) should be like this:
$('#Field2').value(calculateDays($('#Field1').val())) or $('#Field2').value(calculateDays($('#Field1').text()))
Here is solution for setting same date in second field.
Link:jquery: using two datepicker with two fields ( field 1 , field2 + 1 day ) like booking.com
Change the format according to your need.

Changing date entered in textbox to another format using javascript asp.net

I've been looking at forums and tutorials all day, and I can't seem to figure this out. I'm 100% new to asp.net and web design (html, etc); I have been using winforms and vb.net for a few months now.
I have a textbox (ID=DOBTextbox) on a page, and I'm trying to implement javascript code that, when the textbox text length is at least 6 chars (or better yet, can be evaluated as a date), the text changes to a specific date format (preferably MMM dd, yyyy, but I'd be willing to use a built-in javascript date converter function that gets it close). I want to use javascript because I want it to be client-driven.
Following many of the examples along these lines, I understand that I need to create a function in my source file, and I can add an attribute to my code-behind file.
<script type="text/javascript">
function reformatDate(inputDate) {
var outputDate = inputDate.toString();
return outputDate;
}
</script>
And in my code-behind:
DOBTextBox.Attributes.Add("onblur", "reformatDate('" & DOBTextBox.Text & "')")
However, nothing happens when I leave the textbox.
Note: I used "onblur" because I kept trying things out. My first preference is an event that fires when the user changes the text of the textbox. Also, I used ".tostring()" in my function because I got an error saying that todatestring() wasn't recognized (I think todatestring() output is closer to the format I'd like).
Thanks in advance for any help!!!
You probably want this:
DOBTextBox.Attributes.Add("onblur", "reformatDate(this.value);")
With your code, you're trying to combine ASP.NET code and javascript. ASP.NET is static when sent to the browser, javascript is dynamic. When you use your code, you're hardcoding the value of the textbox at the time your ASP.NET code is run into the attribute. So the HTML will probably render as something like:
<input type="text" id="whatever" name="whatever" value="10/24/2001" onblur="reformatDate('10/24/2001')" />
With my change, it will make javascript grab the textbox's value at the time it is blurred and pass it to the reformatDate function. So it will be rendered as something like:
<input type="text" id="whatever" name="whatever" value="10/24/2001" onblur="reformatDate(this.value)" />
Something you may want is to use onchange, not onblur, so that the function only fires when the textbox's value changes, not just if the textbox is blurred.
UPDATE:
The ASP.NET code needs changed to:
DOBTextBox.Attributes.Add("onblur", "this.value = reformatDate(this.value);")
so that the value of the textbox is re-set to the converted value.
UPDATE2:
Try changing your function to:
function reformatDate(inputDate) {
if (inputDate.length > 5) { // Least amount of characters for possible date
var outputDate = new Date(inputDate); // Convert input to date object
if (!isNaN(outputDate.getTime())) { // Makes sure the date is valid
return outputDate.toDateString(); // Return formatted date only if valid
}
}
return inputDate; // Return original value if invalid date
}

Categories