Calculate date from months form - javascript

On my form, I have three fields.
Date of Issue
Validity Period (Months)
Expiry Date
I would like if you enter the date of issue and the validity period fields, The expiry date field to calculate and fill itself. How can I achieve this? The validity period may vary. Thanks in advance.
<div class="tarehe" data-validate = "Date of Issue is required">Date of Issue
<input class="inputpekee" type="date" name="issue_date" placeholder="Date of Issue">
</div>
<div class="tarehe" data-validate = "Validity Period is required">
<input class="inputpekee" type="number" name="validity" placeholder="Validity Period(Months)" min="1" max="60">
</div>
<div class="tarehe" data-validate = "Expiry Date is required">Expiry Date
<input class="inputpekee" type="date" name="expiry_date" placeholder="Expiry Date">
</div>
I expect the format to be dd/mm/yyyy

Here's a way using moment.js
let dateOfIssue = moment();
let validityMonths = 48;
let expiryDate = moment(dateOfIssue).add(validityMonths, 'months');
let el = document.getElementById('expiryDate');
el.innerHTML = expiryDate.format('DD/MM/YYYY');
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
</head>
<body>
<p id="expiryDate"></p>
</body>
</html>

No need any library JS can do this easy, just learn documentation :
get Date Value ( valueAsDate ) => https://developer.mozilla.org/fr/docs/Web/API/HTMLInputElement
DateTimeFormat => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
example :
const FormOption = { day: '2-digit', month: '2-digit', year: 'numeric' };
document.getElementById('My-Form').onsubmit = function(evt) {
evt.preventDefault();
console.log('issue_date : ', new Intl.DateTimeFormat('fr-FR', FormOption).format(this.issue_date.valueAsDate) );
console.log('expiry_date : ',new Intl.DateTimeFormat('fr-FR', FormOption).format(this.expiry_date.valueAsDate) );
}
<form id="My-Form">
<label class="tarehe" data-validate="Date of Issue is required">Date of Issue
<input class="inputpekee" type="date" name="issue_date" placeholder="Date of Issue">
</label>
<label class="tarehe" data-validate="Validity Period is required">
<input class="inputpekee" type="number" name="validity" placeholder="Validity Period(Months)" min="1" max="60">
</label>
<label class="tarehe" data-validate="Expiry Date is required">Expiry Date
<input class="inputpekee" type="date" name="expiry_date" placeholder="Expiry Date">
</label>
<button type="submit">get Values</button>
</form>

You can also try it without having to use moment, using setMonth
$('#validity').change(function(){
let dt = new Date($('#issue_date').val());
dt.setMonth( dt.getMonth() + parseInt($(this).val()));
let output = dt.getDate()+'/'+(dt.getMonth()+1)+'/'+dt.getFullYear()
$('#expiry_date').val(output);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="tarehe" data-validate = "Date of Issue is required">Date of Issue
<input class="inputpekee" type="date" id="issue_date" name="issue_date" placeholder="Date of Issue">
</div>
<div class="tarehe" data-validate = "Validity Period is required">
<input class="inputpekee" type="number" id="validity" name="validity" placeholder="Validity Period(Months)" min="1" max="60">
</div>
<div class="tarehe" data-validate = "Expiry Date is required">Expiry Date
<input class="inputpekee" disabled name="expiry_date" placeholder="Expiry Date" id="expiry_date">
</div>

Related

How to disable previous date using HTML5 datetime-local input?

I would simply like to prevent users from entering or disable the previous dates in input datetime-local , is there a way to do this?
Here is what I have done, unfortunately nothing happens on this code:
<input type="datetime-local" class="form-control col-md-6" name="book" required>
<script>
var today = new Date().toISOString().split('T')[0];
document.getElementsByName('book')[0].setAttribute('min', today);
</script>
try this
var today = new Date().toISOString().slice(0, 16);
document.getElementsByName("book")[0].min = today;
<input type="datetime-local" class="form-control col-md-6" name="book" required>
<div class="row">
<div class="col-md-6">
<label for="time_start">{{ __('adminstaticword.timestart') }}:<sup class="redstar">*</sup></label>
<input type="datetime-local" class="form-control" name="time_start" id="time_start" placeholder="Enter time_start" required min="{{date('Y-m-d')}}" value="{{ old('time_start') }}" >
<script>
var today = new Date().toISOString().slice(0, 16);
document.getElementsByName("time_start")[0].min = today;
</script>
</div>

Disable Weekends

Hello I wish you could help block weekends with type date
I have type date:
input class="form-control" type="date" id="date1" min="2021-01-01" name="calendario"
This is not my code this is your answer by user: 1444609
code written by: user:1444609
const picker = document.getElementById('date1');
picker.addEventListener('input', function(e){
var day = new Date(this.value).getUTCDay();
if([6,0].includes(day)){
e.preventDefault();
this.value = '';
alert('Weekends not allowed');
}
});
<input id="date1" size="60" type="date" format="MM/DD/YYYY" placeholder="MM/DD/YYYY" />

How to keep session storage for all form inputs after submission?

How to save all the values from customer? I can only save first name and last name. Can I pass more than 2 inputs in set details? I tried adding date of birth that had input type text in dd/mm/yyyy format but the value was being shown as "undefined".
Java Script
function getDetails(){
if (typeof(Storage)!=="undefined"){
if (sessionStorage.getItem("firstName") !== null){
document.getElementById("firstName").value = sessionStorage.getItem("firstName");
}
if (sessionStorage.getItem("lastName") !== null){
document.getElementById("lastName").value = sessionStorage.getItem("lastName");
}
}
}
function setDetails(firstName, lastName) {
if (typeof(Storage)!=="undefined"){
sessionStorage.setItem("firstName", firstName);
sessionStorage.setItem("lastName", lastName);
}
}
HTML Code
<label for="firstName">First Name</label>
<br>
<input type="text" name="firstName" id="firstName" placeholder= "Enter first name" title="20 characters" />
<br>
<label for="lastName">Last Name</label>
<br>
<input type="text" name="lastName" id="lastName" placeholder= "Enter last name" class="field" required pattern="([A-z]){1,20}" title="20 characters" />
<br>
<label for="dob">Date of Birth</label>
<br>
<input type="text" name="dob" id="dob" maxlength="10" placeholder="dd/mm/yyyy" pattern="\d{1,2}\/\d{1,2}\/\d{4}"/>
Below code will work to set & get "dob" in cookie:
<html>
<body>
<label for="dob">Date of Birth</label>
<br>
<input type="text" name="dob" id="dob" maxlength="10" placeholder="dd/mm/yyyy" pattern="\d{1,2}\/\d{1,2}\/\d{4}"/>
<button onclick = "setDateInCookie();">SetCookie</button>
<button onclick = "getDateFromCookie();">GetCookie</button>
<script>
function setDateInCookie(){
var myDate = document.getElementById("dob").value;
if(typeof(Storage)!=="undefined")
sessionStorage["myDate"] = myDate;
}
function getDateFromCookie(){
var myDate = document.getElementById("dob").value;
if(typeof(Storage)!=="undefined")
{
if (sessionStorage.getItem("myDate") !== null){
document.getElementById("dob").value = sessionStorage.getItem("myDate");
}
}
}
</script>
</body>
</html>
Future Note: Avoid using input type "text" for input type "date". Use the exact input types for not getting any issues in future.

Want to calculate date of birth from a given age

I'm trying to calculate the date of birth from a given age.
My logic is
When we enter an age say '5'. The date of birth will be calculated as exactly 5 years from the current date. Example current date is 20/8/2018.
Then date of birth will be 20/8/2013 if the age is 5.
So below is my code:
function validatedob() {
var dob_value = document.getElementById('dob').value;
var age_value = document.getElementById('age').value;
var current_date = new Date();
var birth_date = new Date();
var birth_year = current_date.getFullYear() - age_value;
var birth_month = current_date.getMonth();
var birth_day = current_date.getDate();
birth_date.setDate(current_date.getFullYear() - age_value);
birth_date.setMonth(current_date.getMonth());
birth_date.setFullYear(current_date.getDate());
document.getElementById('dob').setDate(birth_day);
document.getElementById('dob').setMonth(birth_month);
document.getElementById('dob').setFullYear(birth_year);
}
<div class="form-inline" id="Age">
<label for="age">Age</label>
<input id="age" type="integer" name="age" onchange="validatedob()">
</div>
<div class="form-inline" id="birth">
<label for="DOB">Date of Birth</label>
<input id="dob" type="date" value="Unknown" name="date_of_birth" max="31-12-2030">
</div>
This is not working. I'm not goodwith html properties.
Can someone help me? how to achieve this?
Here is the simple answer:
> d1 = new Date(2018, 00, 01)
Date 2018-01-01T00:00:00.000Z
> d2 = new Date(d1.getFullYear() - 5, d1.getMonth(), d1.getDate())
Date 2013-01-01T00:00:00.000Z
But, I would suggest to use a library such as Luxon.
Date manipulation is an absolute nightmare if you do it by yourself. This video from Computerphile summarizes it better than I could:
https://www.youtube.com/watch?v=-5wpm-gesOY
Here is a really simple solution that works and some changes to your HTML.
Changes to HTML:
The div and label both had the id "age", this must be unique.
type="integer"doesn't exist, so i changed it to type="number".
And value="unknown"isn't the right format "yyy-MM-dd", so i just removed it.
for="DOB"to for="dob", now that works aswell
Code:
HTML
<div class="form-inline">
<label for="age">Age</label>
<input id="age" type="number" name="age"onchange="validatedob()">
</div>
<div class="form-inline" id="birth">
<label for="dob">Date of Birth</label>
<input id="dob" type="date" name="date_of_birth" max="31-12-2030">
</div>
JavaScript
function validatedob() {
var age_value = document.getElementById("age").value;
var current_date = new Date();
var birth_date = new Date(current_date.getFullYear() - age_value, current_date.getMonth(), current_date.getDate() + 1);
document.getElementById("dob").valueAsDate = birth_date;
}
Here is some sample code for your reference
https://codepen.io/ji_in_coding/pen/wEvoMK
<div class="form-inline" id="Age">
<label for="age">Age</label>
<input id="age" type="integer" name="age" onchange="validatedob()">
</div>
<div class="form-inline" id="birth" >
<label for="DOB">Date of Birth</label>
<input id="dob" type="input" name="date_of_birth">
</div>
Javascript
function validatedob()
{
var age_value = document.getElementById("age").value;
var today = new Date();
var calculated_birthday = new Date(
parseInt(today.getFullYear())+parseInt(age_value),
today.getMonth(),
today.getDate());
document.getElementById("dob").value = calculated_birthday.toLocaleDateString("en-US");
}
You're issue is that you are trying to setDate and cie on a HTMLElement. The input dob expect a string formatted as yyyy-MM-dd. You can try something like that:
var $dob = document.getElementById('dob');
var $age = document.getElementById('age');
function validatedob() {
var age = $age.value;
var date = new Date();
date.setFullYear(date.getFullYear() - age);
$dob.value = formatDate(date);
}
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}
<div class="form-inline" id="Age">
<label for="age">Age</label>
<input id="age" type="integer" name="age" onchange="validatedob()">
</div>
<div class="form-inline" id="birth">
<label for="DOB">Date of Birth</label>
<input id="dob" type="date" value="Unknown" name="date_of_birth" max="31-12-2030">
</div>
PS: For performance purpose avoid to repeat document.getElementById(...) in each method call. Do it once as done in my example.

How to subtract two text box values and display in another text box using Javascript

I want to fins the range between two number entered in a textbox and display it in another text box.
I am using the event onBlur.
Initially i got NaN in the result textbox.
Later I used ParseInt now no value is getting displayed.
My code :
<script type="text/javascript">
function countRows(){
var rows=document.getElementById("rows");
var startMsisdn=parseInt(document.getElementByName("startmsisdn").value);
var endMsisdn=parseInt(document.getElementByName("endmsisdn").value);
rows.value=endMsisdn-startMsisdn;
}
</script>
HTML CODE :
<div class="col-md-4">
<label>MSISDN Start Range </label> <input class="form-control"
type="text" name="startmsisdn"
placeholder="MSISDN Starting Range" required>
</div>
<div class="col-md-4">
<label>MSISDN End Range </label> <input class="form-control"
type="text" name="endmsisdn" placeholder="MSISDN Ending Range"
required>
</div>
</div>
<br>
<div class="row">
<div class="col-md-4">
<label>IMSI Start Range </label> <input class="form-control"
type="text" name="startimsi" placeholder="IMSI Starting Range"
required>
</div>
<div class="col-md-4">
<label>IMSI End Range </label> <input class="form-control"
type="text" name="endimsi" placeholder="IMSI Ending Range"
required onblur="countRows()">
</div>
<div class="col-md-4">
<label>No of rows </label> <input class="form-control"
type="text" name="rows" id="rows"
required>
</div>
Add default value for empty field
Try to get element by id for input field;
like this
Html
div class="col-md-4">
<label>IMSI Start Range </label>
<input class="form-control"
type="text" id="startimsi" name="startimsi" placeholder="IMSI Starting Range"
required>
</div>
<div class="col-md-4">
<label>IMSI End Range </label>
<input class="form-control"
type="text" id="endimsi" name="endimsi" placeholder="IMSI Ending Range"
required onblur="countRows()">
</div>
Javascript
var startMsisdn=parseInt(document.getElementById("startmsisdn").value) || 0;
var endMsisdn=parseInt(document.getElementById("endmsisdn").value) || 0;
You have two issues here. parseInt may return NaN, so any value you add to it will also always return NaN. The second issue is there is no getElementByName method (singular). It's getElementsByName which returns an array-like object:
function countRows(){
var rows=document.getElementById("rows");
var startMsisdn=parseInt(document.getElementsByName("startmsisdn")[0].value, 10) || 0;
var endMsisdn=parseInt(document.getElementsByName("endmsisdn")[0].value, 10) || 0;
rows.value=endMsisdn-startMsisdn;
}
You may notice that I added an extra parameter to your parseInt too. This is to force non-ES5 compliant browsers to parse as decimal - they may default to using octal for parsing which will result in unexpected results if a zero-prefixed value is entered.
Working Example
function countRows(){
var rows=document.getElementById("rows");
var startMsisdn=parseInt(document.getElementsByName("startmsisdn")[0].value, 10) || 0;
var endMsisdn=parseInt(document.getElementsByName("endmsisdn")[0].value, 10) || 0;
rows.value=endMsisdn-startMsisdn;
}
<div class="col-md-4">
<label>MSISDN Start Range </label>
<input class="form-control" type="text" name="startmsisdn" placeholder="MSISDN Starting Range" required>
</div>
<div class="col-md-4">
<label>MSISDN End Range </label>
<input class="form-control" type="text" name="endmsisdn" placeholder="MSISDN Ending Range" required>
</div>
<br>
<div class="row">
<div class="col-md-4">
<label>IMSI Start Range </label>
<input class="form-control" type="text" name="startimsi" placeholder="IMSI Starting Range" required>
</div>
<div class="col-md-4">
<label>IMSI End Range </label>
<input class="form-control" type="text" name="endimsi" placeholder="IMSI Ending Range" required onblur="countRows()">
</div>
<div class="col-md-4">
<label>No of rows </label>
<input class="form-control" type="text" name="rows" id="rows" required>
</div>
</div>
try this by replacing NaN with 0 ..
function countRows(){
var rows = document.getElementById("rows");
var startMsisdn=document.getElementById("startmsisdn").value;
if(startMsisdn =='' ){ startMsisdn =0;}
var endMsisdn=document.getElementById("endmsisdn").value;
if(endMsisdn =='' ){ endMsisdn =0;}
rows.value= parseInt(endMsisdn) - parseInt(startMsisdn);
}
HERE is the FIDDLE
Add These line of code in script its will work fine.
function countRows() {
var rows = document.getElementById("rows");
var startMsisdn = parseInt(document.getElementsByName("startmsisdn")[0].value);
var endMsisdn = parseInt(document.getElementsByName("endmsisdn")[0].value);
rows.value = endMsisdn - startMsisdn;
}

Categories

Resources