How to use js-datepicker in multiple elements using class - javascript

I'm using js-datepicker for datepicker on my project. I chose this library because I wanted to use vanilla JS on my application so I won't be using JQuery UI datepickers nor HTML5 input date(for browser compatibility).
The problem is I have multiple inputs that will be datepicker but when I create an instance using their classes the datepicker is only binded on the first element with that class
HTML inputs
<input type="text" class="form-control test-datepickers" id="dp1">
<input type="text" class="form-control test-datepickers" id="dp2">
<input type="text" class="form-control test-datepickers" id="dp3">
<input type="text" class="form-control test-datepickers" id="dp4">
JS instantiation
const test_dp = datepicker('.test-datepickers', {
formatter: (input, date, instance) => {
const offset = date.getTimezoneOffset();
date = new Date(date.getTime() - (offset*60*1000));
input.value = date.toISOString().split('T')[0];
},
showAllDates: true,
minDate: new Date()
});
Please do not suggest to create an instance by id cause I'm creating these inputs dynamically (when the a button is pressed).

You can query for all the elements with the given class and then loop over them to add the datepicker.
const items = document.querySelectorAll(".test-datepickers");
for(let i=0; i<items.length; i++){
const node = items[i];
datepicker(node, {
formatter: (input, date, instance) => {
const offset = date.getTimezoneOffset();
date = new Date(date.getTime() - (offset * 60 * 1000));
input.value = date.toISOString().split('T')[0];
},
showAllDates: true,
minDate: new Date()
});
}
<script src="https://unpkg.com/js-datepicker/dist/datepicker.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/js-datepicker/dist/datepicker.min.css">
<input type="text" class="form-control test-datepickers" id="dp1">
<input type="text" class="form-control test-datepickers" id="dp2">
<input type="text" class="form-control test-datepickers" id="dp3">
<input type="text" class="form-control test-datepickers" id="dp4">
For dynamic usage,
const items = document.querySelectorAll(".test-datepickers");
document.querySelector("button").addEventListener("click",function(){
let inp = document.createElement("input")
inp.setAttribute("type","text");
document.body.appendChild(inp);
datepicker(inp, {
formatter: (input, date, instance) => {
const offset = date.getTimezoneOffset();
date = new Date(date.getTime() - (offset * 60 * 1000));
input.value = date.toISOString().split('T')[0];
},
showAllDates: true,
minDate: new Date()
});
})
for(let i=0; i<items.length; i++){
const node = items[i];
datepicker(node, {
formatter: (input, date, instance) => {
const offset = date.getTimezoneOffset();
date = new Date(date.getTime() - (offset * 60 * 1000));
input.value = date.toISOString().split('T')[0];
},
showAllDates: true,
minDate: new Date()
});
}
<script src="https://unpkg.com/js-datepicker/dist/datepicker.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/js-datepicker/dist/datepicker.min.css">
<button>Add date</button>
<br/>
<input type="text" class="form-control test-datepickers" id="dp1">
<input type="text" class="form-control test-datepickers" id="dp2">
<input type="text" class="form-control test-datepickers" id="dp3">
<input type="text" class="form-control test-datepickers" id="dp4">

Related

Local Variable to Global Variable in JavaScript

I am developing a web page where the Months will be calculated after entering the Date from the Input Field.
I want to take the value of "diffMonthsGlobe" to another function where this calculated value is going to the database.
But as I have seen few answers in StackOverflow and try to do the same but still in my case it is not possible
var diffMonthsGlobe;
function getValue() {
// Getting Values......
const startDate = document.getElementById("startDate").value;
const endDate = document.getElementById("endDate").value;
// Calculating Time Period.......
const date1 = new Date(endDate);
const date2 = new Date(startDate);
var diffMonth = (date2.getTime() - date1.getTime()) / 1000;
diffMonth /= 60 * 60 * 24 * 7 * 4;
diffMonths = Math.abs(Math.round(diffMonth));
diffMonthsGlobe = diffMonths;
// Printing Values......
console.log(startDate);
console.log(endDate);
console.log(diffMonths + " Months");
return diffMonthsGlobe;
}
getValue();
console.log(diffMonthsGlobe + " Months");
<input type="date" class="form-control" placeholder="Start Date *" name="startDate" id="startDate" required onchange="getValue()" />
<input type="date" class="form-control" placeholder="End Date *" name="endDate" id="endDate" required onchange="getValue()" />
Use a form so the required works
Use the submit event to get the value and send to server
const getValue = function() {
// Getting Values......
const startDate = document.getElementById("startDate").value;
const endDate = document.getElementById("endDate").value;
// Calculating Time Period.......
const date1 = new Date(endDate);
const date2 = new Date(startDate);
var diffMonth = (date2.getTime() - date1.getTime()) / 1000;
diffMonth /= 60 * 60 * 24 * 7 * 4;
diffMonths = Math.abs(Math.round(diffMonth));
diffMonthsGlobe = diffMonths;
// Printing Values......
console.log(startDate);
console.log(endDate);
return diffMonthsGlobe;
}
window.addEventListener("load", function() { // page load
document.getElementById("myForm").addEventListener("submit", function(e) {
e.preventDefault(); // stop submission
const monthDiff = getValue();
console.log(monthDiff + " Months");
// here you can fetch or otherwisde ajax to server
})
})
<form id="myForm">
<input type="date" class="form-control" placeholder="Start Date *" name="startDate" id="startDate" required />
<input type="date" class="form-control" placeholder="End Date *" name="endDate" id="endDate" required />
<input type="submit" />
</form>

It is possible to add an integer input with a time type input and result to a time type input?

As I mention in the title I have three input in HTML:
<input type="number" name="time" id="time">
<input type="time" name="hour_start" id="hour_start">
<input type="time" name="hour_final" id="hour_final">
and JS:
<script>
$("#time").change(function () {
var time = $('#time').val();
var start = $('#hour_start').val();
var convert = Math.floor(time/60);
var final = start + convert;
$('#hour_final').val(final);
});
</script>
The calculation is done without using a button.
Enter image description here
Javascript answser ( as you asking) :
const myForm = document.querySelector('#my-Form')
, z2 = v=>('00'+v).slice(-2) // like padStart(2.'0')
myForm.time.oninput=_=>
{
let inDate = myForm.hour_start.valueAsDate
, h_UTC = inDate.getUTCHours()
, m_UTC = inDate.getUTCMinutes()
, nTim = (h_UTC * 60) + m_UTC + myForm.time.valueAsNumber
h_UTC = Math.trunc(nTim/60) % 24
m_UTC = nTim % 60
inDate.setUTCHours(h_UTC)
inDate.setUTCMinutes(m_UTC)
myForm.hour_final.valueAsDate = inDate
}
myForm.onsubmit=e=>
{
e.prventdefault() // just for test
}
<form action="xxx" id="my-Form">
<input type="number" name="time" value="0" min="0" max="2000">
<input type="time" name="hour_start" value="13:30">
<input type="time" name="hour_final" value="13:30">
</form>

Need value of datepicker as part of variable

I need to have the value from a datepicker to a part of a variable. The value from the datepicker must be inserted instead of getAge("02/20/2017") in the this code. the date has to be changed when datepicker is used, then "leeftijd" chages as well of course
function getAge(dateString) {
var birthdate = new Date(dateString).getTime();
var now = new Date().getTime();
var n = (now - birthdate) / 1000;
if (n < 604800) { // less than a month
var week_n = Math.abs(n / 604800).toFixed(2);
return week_n;
} else if (n < 63113852) { // less than 24 months
var month_n = Math.abs(n / 2629743).toFixed(2);
return month_n;
}
}
var age = getAge("02/20/2017");
document.getElementById("age").value = age;
<form name="id">
<input id="age" class="appTextfield" type="text" name="element1" placeholder="age" value="">
<input id="weight" class="appTextfield" type="text" name="element2" placeholder="weight" value="">
<p>Date: <input type="date" id="datepicker" size="30" onchange="getAge()"></p>
</form>
I tried lots of things but i can't get it to work... i must be doing something wrong. Any solutions to get it working?
This code will help you
function getAge(dateString) {
var birthdate = new Date(dateString).getTime();
var now = new Date().getTime();
var n = (now - birthdate) / 1000;
if (n < 604800) { // less than a month
var week_n = Math.abs(n / 604800).toFixed(2);
return week_n;
} else if (n < 63113852) { // less than 24 months
var month_n = Math.abs(n / 2629743).toFixed(2);
return month_n;
}
}
function calculateAge(dateString) {
var age = getAge(dateString);
document.getElementById("age").value = age;
}
<form name="id">
<input id="age" class="appTextfield" type="text" name="element1" placeholder="age" value="">
<input id="weight" class="appTextfield" type="text" name="element2" placeholder="weight" value="">
<p>Date: <input type="date" id="datepicker" size="30" onchange="calculateAge(this.value)"></p>
</form>

How can I calculate dates in jQuery, and set an input date's value to that?

I have this html:
<input class="smalldatepicker" type="date" id="datepickerFrom" value="2016-09-04">
</input>
<label class="cccsfont"> to </label>
<input type="date" class="smalldatepicker" id="datepickerTo" value="2016-09-10">
</input>
Which sets "datepickerTo" to the last Saturday (this is based on today's date of Thursday, 9/15) and "datepickerFrom" to the Sunday before that.
This is manually added, though; I want to do it programmatically, in jQuery, something like:
var lastSat = getLastSaturday(); // return in form "YYYY-MM-DD"
var sundayBeforeLastSat = getSundayBeforeLast(lastSat); // " "
$("#datepickerTo").val(lastSat);
$("#datepickerFrom").val(sundayBeforeLastSat);
I think this should work, but I don't know what to put in the functions:
function getLastSaturday() {
return ???;
}
function sundayBeforeLastSat(lastSat) {
return ???;
}
If you don't want to use any library like moment.js or other
Try this :
$(function(){
var lastSat = getLastSaturday(); // return in form "YYYY-MM-DD"
var sundayBeforeLastSat = getSundayBeforeLastSat(lastSat); // " "
console.log("Last satuarday: "+lastSat);
console.log("Last Sunday: "+sundayBeforeLastSat);
$("#datepickerTo").val(lastSat);
$("#datepickerFrom").val(sundayBeforeLastSat);
});
function getLastSaturday() {
newDate= new Date();
daysAfterSat = newDate.getDay()+1;
lastSat = new Date(newDate.setDate(newDate.getDate()-daysAfterSat));
dateString = lastSat.getFullYear()+ "-"+('0' + (lastSat.getMonth()+1)).slice(-2) + '-'+('0' + lastSat.getDate()).slice(-2);
return dateString;
}
function getSundayBeforeLastSat(lastSat) {
date = new Date(lastSat);
lastSun = new Date(date.setDate(date.getDate()-6));
dateString = lastSun.getFullYear()+ "-"+('0' + (lastSun.getMonth()+1)).slice(-2) + '-'+('0' + lastSun.getDate()).slice(-2);
return dateString;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input class="smalldatepicker" type="date" id="datepickerFrom" value="">
</input>
<label class="cccsfont"> to </label>
<input type="date" class="smalldatepicker" id="datepickerTo" value="">
</input>
</form>
Here is a Date manipulation in ES6.
jQuery may have some module that can do it?
Otherwise moment.js is a fine library that may do it for you?
function pad(num) {
return `0${num}`.slice(-2);
}
// d is a Date object,returns 'YYYY-MM-DD'
function format(d) {
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
}
function day(d, dow) {
d.setTime(d.getTime() + (dow - d.getDay()) * 86400000);
return d;
}
// dateString is of form 'YYYY-MM-DD'
function parse(dateString) {
const args = dateString.split('-');
args[1] -= 1;
return args;
}
function getLastSaturday(...dateArgs) {
return format(day(new Date(...dateArgs), -1));
}
function getSundayBeforeLast(lastSat) {
return format(day(new Date(...parse(lastSat)), 0));
}
const lastSat = getLastSaturday();
const sundayBeforeLastSat = getSundayBeforeLast(lastSat);
$('#datepickerTo').val(lastSat);
$('#datepickerFrom').val(sundayBeforeLastSat);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="smalldatepicker" type="date" id="datepickerFrom">
<label class="cccsfont">to</label>
<input type="date" class="smalldatepicker" id="datepickerTo">
And using moment.js
function getLastSaturday(...dateArgs) {
return moment(dateArgs).day(-1).format('YYYY-MM-DD');
}
function getSundayBeforeLast(lastSat) {
return moment(lastSat).day(0).format('YYYY-MM-DD');
}
const lastSat = getLastSaturday();
const sundayBeforeLastSat = getSundayBeforeLast(lastSat);
$('#datepickerTo').val(lastSat);
$('#datepickerFrom').val(sundayBeforeLastSat);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.0/moment.js"></script>
<input class="smalldatepicker" type="date" id="datepickerFrom">
<label class="cccsfont">to</label>
<input type="date" class="smalldatepicker" id="datepickerTo">

How to make Datebox Jquery Mobile Input field clickable?

I have two date fields. Field 2 works fine. Clicking anywhere on the input type date for second fields opens the calendar. But the same is not working for first date field. When I click on the calendar icon for date field it opens the calendar but I want that calendar should pop up when I click anywhere on the date field for field 1 as well.
Why does it works for the second field but not for the first field.
Also the default date is not getting set to todays date.
http://jsfiddle.net/KJ4e5/3/
HTML
<body>
<div id="doc">
<table>
<tr>
<td>
<input name="date1" id="date1" type="date" data-role="datebox" data-options='{"mode": "calbox","dateFieldOrder":["d","m","y"], "useNewStyle":true,"overrideDateFormat": "%d/%m/%Y", "afterToday":true}' />
</td>
<td>
<input name="date2" id="date2" type="date" data-role="datebox" data-options='{"mode": "calbox","dateFieldOrder":["d","m","y"], "useNewStyle":true,"overrideDateFormat": "%d/%m/%Y", "afterToday":true}'/>
</td>
</tr>
</table>
</div></body>
//JS
$( document ).on( "pageinit", "#doc", function() {
var defaultPickerValue = new Date();
var today = defaultPickerValue.getDate() + "/" + (defaultPickerValue.getMonth()+1) + "/" + defaultPickerValue.getFullYear();
$('#date1').val(today);
$('#date2').val(today);
$('#date1').on('change', function() {
if ( $('#date2')) {
$('#date2').val($('#date1').val());
var temp = new Date();
var start = $('#date1').datebox('getTheDate');
var diff = parseInt((start - temp) / ( 1000 * 60 * 60 * 24 ));
diffstrt = (diff * -1)-1;
$("#date2").datebox("option", {
"minDays": diffstrt
});
}
});
});
I can't explain why the 2 boxes act differently, but if you explicitly assign the useFocus option to the boxes, they will both work:
<input name="date1" id="date1" type="date" data-role="datebox"
data-options='{"mode": "calbox","dateFieldOrder":["d","m","y"],
"useNewStyle":true, "overrideDateFormat": "%d/%m/%Y",
"afterToday":true, "centerHoriz": true, "useFocus": true}' />
Here is your updated FIDDLE
In the fiddle I have also changed your script a little. With the datebox you can set the dates as follows:
var defaultPickerValue = new Date();
$('#date1').datebox('setTheDate', defaultPickerValue).trigger('datebox', {'method':'doset'});
$('#date1').on('change', function () {
if ($('#date2')) {
var temp = new Date();
var start = $('#date1').datebox('getTheDate');
$('#date2').datebox('setTheDate', start).trigger('datebox', {'method':'doset'});
var diff = parseInt((start - temp) / (1000 * 60 * 60 * 24));
diffstrt = (diff * -1) - 1;
$("#date2").datebox("option", {
"minDays": diffstrt
});
}
});

Categories