How to add dates from the date updated in text box - javascript

I am using a form to input date in text box format (mm/dd/yyyy) and the next text box I will enter how many days to add. This is should automatically calulate the no of days and display in 3rd text box. E.g
Text Box1: Input date (mm/dd/yyyy)
Text Box2: Input no of days
Text Box3: textbox1 value+textbox3 value
I need help to add dates.
I tried in onblur event in textbox2 using Javascript function
Code:
//text box2 event
onblur="adddate(this.value)"
//javascript fn
function adddate(a) {
var rdat=document.telstoe.rdate.value;
if(a==2) {
document.telstoe.tdate.value=rdat+2;
}
}
Input Values:
Textbox 1: 11/14/2012 (mm/dd/yyyy)
Textbox 2: 2 or 3 or 4
The output should be: only the days should be counted and displayed and I am getting like 1/14/2012*2*
Please help with the correct code

try this:
function adddate(a) {
var tdate = document.telstoe.rdate.value;
var theDate=new Date(tdate);
theDate.setDate( theDate.getDate() + a );
document.telstoe.tdate.value=(theDate.getMonth() + 1) + "/" + theDate.getDate() + "/" theDate.getFullYear();
}
and use this page for your reference:
http://www.w3schools.com/jsref/jsref_obj_date.asp
Please have a look at the object reference! It would be preferred for your own sake, to learn the javascript Date object. Good luck.

You can use a Date object to parse the date and add days to it:
var date = new Date(document.telstoe.rdate.value);
date.setDate(date.getDate() + 1);
document.telstoe.tdate.value = (date.getMonth() + 1) + "/" + date.getDate() + "/" date.getFullYear().toString().substring(2);
Or use something like the jQuery UI datepicker to format the date.

Related

Broken Delivery Estimate Calculator

I'm hoping someone can help me figure out how to code an app that allows you to select a mailing date with jquery datepicker, select Standard or First-class shipping from a dropdown, and calculate an estimated delivery date window (7-12 Days for Standard, 3-5 Days for First-class).
I had it working when the "Mailing in" [number] "Days" accepted a string input but then it broke when I added code for the datepicker.
I also need to keep weekends & holidays excluded from the shipping calculation.
Here's a link to the full pen: https://codepen.io/allyjfuller/pen/oNXvwJL
$('#calculateShippingEstimate').click(function( event ) {
//Prevent button from 'submitting' and reloading the page
event.preventDefault();
//Capture the mailing date
var $mailingDate = $("#mailingDate").val();
var $postageType = $("#postageType").val();
var $shipStateShippingDuration = eval('data.shipTimes.' + $postageType);
var $totalShippingTime = parseInt($mailingDate) + parseInt($shipStateShippingDuration);
//Create the date
var date = new Date();
var month = date.getMonth()+1;
var day = date.getDate() + parseInt($totalShippingTime);
var year = date.getFullYear();
<form>
<section>
<label>Mailing on</label>
<input id="mailingDate" placeholder="number"></input>
</section>
<section>
<label>Postage:</label>
<select id="postageType">
<option value="Standard">Standard</option>
<option value="FirstClass">First-Class</option>
</select>
</section>
<input class="button" id="calculateShippingEstimate" type="submit" value="Get Estimated Delivery Date"></input>
<div class="results"></div>
</form>
Looking through your code snippet it seems like you're trying to hand roll a lot of features that already exist within the JS Date framework.
Once you get the starting date and the number of days for shipping, you can add those days together to create a final shipping date. From there and within a loop, you may go day by day and check whether the current date index is a weekday or not (using Date.getDay()).
With that you may check for Saturday [6] and Sunday [0] and then add days needed on top of the final date.
I've included my version of the code below with some console debugging but have not added code holidays. Holidays may be checked for using an array or map. Get all the holiday dates for a year and then have the current index check the holiday array/map to see if there are any matches. If there are, add another day to the final date.
The function for addDays is pulled from here. It adds some explanation which I think you'll find helpful.
function addDays(date, days) {
const copy = new Date(Number(date))
copy.setDate(date.getDate() + days)
return copy
}
// FINAL SHIPPING ESTIMATE
$('#calculateShippingEstimate').click(function( event ) {
event.preventDefault();
let mailingDateVal = $("#mailingDate").val();
let shippingDuration = data.shipTimes[$("#postageType").val()];
let mailingDate = new Date(mailingDateVal);
console.log("final Date: " + addDays(mailingDate, shippingDuration));
let finalDate = addDays(mailingDate, shippingDuration)
let mailingDateIndex = new Date(mailingDate);
while(mailingDateIndex <= finalDate) {
console.log("current mailDateIndex: " + mailingDateIndex)
if (mailingDateIndex === finalDate) {
break;
}
// Weekend
console.log(mailingDateIndex.getDay());
if (mailingDateIndex.getDay() == 0 || mailingDateIndex.getDay() == 6) {
console.log("weekend day hit! Adding day to final...")
finalDate = addDays(finalDate, 1);
}
mailingDateIndex = addDays(mailingDateIndex, 1);
}
});

How to have javascript presets today's date in HTML form

I am developing a project with Django.
I have an html webpage containing a form which has a date field.
I want javascript compile it with today's date as soon as my user lands on that webpage, so that he/she gets a kind of "default date".
I have in my html page (templates/aggiungi_terminologia.html), the date field:
<div class="form-group">
<label for="glossary_entry_input_21">Data di inserimento della terminologia</label>
<small id="inputHelp" class="form-text text-muted">Compilare solo se รจ nota la data di pubblicazione del documento fonte, altrimenti inserire la data di oggi.</small>
<input name="Data_inserimento_entry" type="date" value="01/01/1900" class="form-control" id="date_to_turn_into_today" placeholder="">
</div>
and then the javascript call at the end of the form:
{% load static %}
<script> src="{% static 'get_today_date.js' %}"</script>
And then, inside my javascript function (static/js/get_today_date.js):
var today = moment().format('DD/MM/YYYY');
document.getElementById("date_to_turn_into_today").value = today;
and since I am using moment.js, I added 'moment' in settings.py> INSTALLED_APPS ,
and to install moment I run on my console:
pip install django-staticfiles-moment
But when I run the server, all I get on that field is this:
My console is returning:
WARNINGS: app_glossario.glossary_entry.Data_inserimento_entry:
(fields.W161) Fixed default value provided.
HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to
have the current date as default, use django.utils.timezone.now
Why javascript is not replacing the date?
How can I make it work?
NOTE: the problem lies in the connection between js, html and django
Continue from comment about duplicated or not, take a look:
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear()+"-"+(month)+"-"+(day);
document.getElementById('inputDate').value = today;
<input type="date" id="inputDate" />
Please check this also.
I've seen similar behavior (where the input field shows a date placeholder instead of my desired date) when I provided a date string that was incorrectly formatted. The input element seems to need a format like yyyy-mm-dd.
Here's a pretty intuitive solution using vanilla JS. The default value of the input element will be the (locale-specific) date.
(And most of the further info you might want about JS Dates can be found here on MDN.)
const
// Selects input element
dateInput = document.getElementById("date"),
// Defines Date object
date = new Date(),
// Extracts component parts of Date object
year = date.getFullYear(),
month = date.getMonth(),
day = date.getDate(),
// Defines a function to add a leading zero if needed
pad = part => part < 10 ? "0" + part : part,
// Formats date to meet the `input` element's expectations -- like: `yyyy-mm-dd`
// (Adds +1 to month b/c `getMonth()` uses a zero-based array)
dateString = year + "-" + pad(month + 1) + "-" + pad(day);
// Inserts date string into input element
dateInput.defaultValue = dateString;
// Repeats this process for the "time" parts
/*
const
timeInput = document.getElementById("time"),
hours = date.getHours(),
minutes = date.getMinutes(),
seconds = date.getSeconds(),
timeString = pad(hours) + ":" + pad(minutes) + ":" + pad(seconds);
timeInput.defaultValue = timeString;
*/
<input id="date" type="date" />
<!--
// Optional input for time
<input id="time" type="time" />
-->
SOLVED
Here is what I did.
In a javascript file called
get_today_date.js
stored at path
static/js/get_today_date.js
I inserted
function get_today_date() {
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear()+"-"+(month)+"-"+(day);
document.getElementById('date_to_turn_into_today').value = today;
}
as suggested here https://stackoverflow.com/a/57953522/7658051 .
Then in the HTML page, before the closing </body> tag, I inserted
{% load static %}
<script type="text/javascript" src={% static "js/get_today_date.js" %}></script>
<script> get_today_date() </script>
and it works perfectly.
There was no neet to install the module moment, and even if my console returns
WARNINGS: app_glossario.glossary_entry.Data_inserimento_entry: (fields.W161) Fixed default value provided. HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use django.utils.timezone.now
my app works fine.
The previous code did not work just because I forgot to call the function in HTML, so I just had to add
get_today_date()
But in the end I am not sure if I correctly installed the moment module required for the previuos javascript script.

How to set selected date on Jquery Calendar Plugin

So I am using the calendar app on a page that has a set date. I have it so when you click on the calendar, whatever is in the input that has the date, gets changed to the date you clicked on.
When you load into the page I want whatever date that is in the input to be what the calendar is set to. Thanks.
LINK TO PLUGIN - https://www.jqueryscript.net/time-clock/Simple-jQuery-Calendar-Date-Picker-Plugin-DCalendar.html
var pageDate = "4/04/2018";
<input class="date">
$('.date').val(pageDate);
// Make above date the selected date
// Code below is for setting input to date you select. Currently works.
$('.box').dcalendarpicker({
format: 'mm-dd-yyyy'
}).on('datechanged', function(e) {
console.log('Date change');
var d = e.date;
selectedDate = moment(d, 'MM-DD-YYYY');
var theDate = selectedDate._i;
$('.date').val(theDate);
var weekdayLongform = selectedDate.format("dddd, MMMM");
var dateLongform = selectedDate.format(" D");
var yearLongform = selectedDate.format(" YYYY");
});
Just set the date as the value of the input (in the same format specified in the plugin initialization). That will do the trick.
<!-- value specifid as mm-dd-yyyy -->
<input class="date" value="03-11-2018">

Date Picker Input

How can I validate my HTML date input so only certain dates of the week can be selected? I've seen this before on some booking websites. A date-picker calendar appears and days that the event is unavailable are grey out and cannot be selected.
I'm not sure where to start and I want to do this as my current project requires date input validation. The event is only available 3 days a week so it wouldn't make sense for the client to select a date when there is no event on.
Example, days are Monday, Wednesday and Friday so picking the Thursday 30th Nov shouldn't be an option.
With the first-line question in mind, what would be the simplest programming language to create a date-picker on to go with a data driven website?
If you are using jquery date picker:
<script>
var disableDates = ["22-11-2017", "23-11-2017"];
function disable(date) {
// convert it to my formate
dateToCheck = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
if ($.inArray(dateToCheck , disableDates) == -1) {
return [true, ""];
} else {
return [false, "", "disabled"];
}
}
$(function() {
$("#eventDate").datepicker({
dateFormat: 'dd-MM-yy',
beforeShowDay: disable
});
});
</script>

how to append - automatically in date format in jquery

I have a text box i need to append "-" in date format
Like I type DD-MM-YYYY in text box
when users enter Date-(This should automatically come) than month (- this should automatically come ) and than later year
so when i enter something in text box like this
29-06-1992
How to do it in JavaScript or Jquery
Try this one:
$(document).on('keyup','#your_textbox_id',function(){
if($('#your_textbox_id').val().length == 2){
$('#your_textbox_id').val( $('#your_textbox_id').val().substring(0,2) +'-')
}
else if($('#your_textbox_id').val().length == 5){
$('#your_textbox_id').val( $('#your_textbox_id').val().substring(0,5) +'-')
}
})

Categories

Resources