I would like to add a number of day to the date that I give to my form then display it in an empty input.
<div class="col">
<input type="date" [(ngModel)]="date" />
<input type="number" min="1" max="31" [(ngModel)]="day"/>
</div>
<div class="col">
<input type="button" value="Calculate" (click)="addDays()"/>
</div>
<div class="col">
<input type="text" [(ngModel)]="result"/>
</div>
The code behind
day: number;
date: Date;
result: Date;
addDays(){
this.result = this.date.setDate(this.date + this.day);
console.log(this.result);
}
I get an error: this.date.setDate is not a function because I can't add a number to a date. I checked some topics but didn't get solutions.
You have to do something like this:
function addDays(date, days) {
var newDate = new Date(date);
newDate.setDate(newDate.getDate() + days);
return newDate;
}
Related
Hi there can you help me solving this,
I have this code here
<div>
<div>
<input type="text" name="" tabindex="0" styling="[object Object]"
placeholder="YYYY/MM/DD" aria-label="date" aria-invalid="false"
valid="1" class="needsclick TextInput__FormStyledTextInput-sc-1o6de9f-0
fsIKy kl-private-reset-css-Xuajs1">
</div>
</div>
<div>
<div>
<input type="text" name="" tabindex="0" styling="[object Object]"
placeholder="YYYY/MM/DD" aria-label="date" aria-invalid="false"
valid="1" class="needsclick TextInput__FormStyledTextInput-sc-1o6de9f-0
fsIKy kl-private-reset-css-Xuajs1">
</div>
</div>
How can i give the input value today's date, with pure javascript, i cant add manually and can't add other classes name or id's because its automatically generated.
Thanks,
Edited,
The script i want to include is in a shopify theme, and the inputs are on a pop-up, maybe this will help you more
This should help:
let date = new Date();
document.getElementsByClassName('needsclick TextInput__FormStyledTextInput-sc-1o6de9f-0 fsIKy kl-private-reset-css-Xuajs1')[0].value = date.getFullYear() +'/'+ date.getMonth() +'/'+ date.getDate();
document.getElementsByClassName('needsclick TextInput__FormStyledTextInput-sc-1o6de9f-0 fsIKy kl-private-reset-css-Xuajs1')[1].value = date.getFullYear() +'/'+ date.getMonth() +'/'+ date.getDate();
<div>
<div>
<input type="text" name="" tabindex="0" styling="[object Object]"
placeholder="YYYY/MM/DD" aria-label="date" aria-invalid="false"
valid="1" class="needsclick TextInput__FormStyledTextInput-sc-1o6de9f-0
fsIKy kl-private-reset-css-Xuajs1">
</div>
</div>
<div>
<div>
<input type="text" name="" tabindex="0" styling="[object Object]"
placeholder="YYYY/MM/DD" aria-label="date" aria-invalid="false"
valid="1" class="needsclick TextInput__FormStyledTextInput-sc-1o6de9f-0
fsIKy kl-private-reset-css-Xuajs1">
</div>
</div>
You can use getElementsByClassName() method to get the elements with class "test" and then use "Date()" to pass the date.
inputs = document.getElementsByClassName("test")
inputs[0].value = new Date();
<div>
<div>
<input class="test" type="text" />
</div>
</div>
<div>
<div>
<input class="test" type="text" />
</div>
</div>
Here you go :
var inputs = document.getElementsByTagName('input');
for (let i = 0; i<inputs.length; i++) {
if (inputs[i].classList.contains('test')) {
let now = new Date();
inputs[i].value = now.getFullYear() +'/'+ now.getMonth() +'/'+ now.getDate();
break;
}
}
<div>
<div>
<input class="test" type="text"/>
</div>
</div>
<div>
<div>
<input class="test" type="text"/>
</div>
</div>
var now = new Date();
document.getElementsByClassName("test")[0].value = now;
document.getElementsByClassName("test")[1].value = now;
const inputs = documemt.querySelectorAll('.test')
for (let i = 0; i < inputs.length; i++) {
inputs[i].value = new Date().getDate()
}
EDIT
If you only want a single input to display the date:
inputs[index] = new Date().getDate()
I'm making a page to easily calculate when I could go home from work. The page should set a start date when loaded. That way I don't have to know when I started working and just open my browser. Then by clicking one of the buttons it should just add some hours.
The example is one of the many things I've tried already. But this one is close I think. Any suggestions are welcome. I didn't include jquery because of the small scale this has.
function reset() {
var date = new Date();
var hour = date.getHours(),
min = date.getMinutes();
hour = (hour < 10 ? "0" : "") + hour;
min = (min < 10 ? "0" : "") + min;
var timestamp = hour + ":" + min;
document.getElementById("start_time").value = timestamp;
}
function add_time_76() {
var start = document.getElementById("start_time").value;
document.getElementById("end_time").value = start + 7, 6;
}
function getTotal() {
var start = document.getElementById("start_time").value;
var end = document.getElementById("end_time").value;
document.getElementById("total").value = end - start;
}
<body onload="reset()">
<p>Start time: <input name="start_time" type="time" /></p>
<p>Time to go home: <input name="end_time" type="time" /></p>
<p>Total hours: <input type="text" name="total" readonly></p>
<button onclick="add_time_76()">Add 7,6h</button>
<button onclick="add_time_8()">Add 8h</button>
<br><br>
<button onclick="getTotal()">Calculate Total</button>
<br><br>
<button onclick="reset()">Reset</button>
</body>
The time fields aren't getting populated when I want them to be.
Just add a id to your inputs.
<p>Start time: <input id="start_time" name="start_time" type="time" /></p>
<p>Time to go home: <input id="end_time" name="end_time" type="time" /></p>
<p>Total hours: <input id="total" type="text" name="total" readonly></p>
I'm a newbie and still at the beginner level of PHP, Javascript, Codeigniter. I'm facing an unexpected result when I try to calculate the time difference between two 12 hours format time inputs.
Here is the HTML,JS
function hitungjam() {
var start = new Date($('#inputJammulai'));
var end = new Date($('#inputJamselesai'));
var s = start.toTimeString();
var e = end.toTimeString();
var diff = e - s;
var jam = Math.floor(diff/1000/60/60);
$('#inputSelisih').val(jam);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div class="form-group">
<div class="form-row">
<div class="col-md-4">
<label for="inputJammulai">Start</label>
<!-- <div class="form-label-group"> -->
<input type="time" name="inputJammulai" id="inputJammulai" class="form-control" required="required">
<!-- </div> -->
</div>
<div class="col-md-4">
<label for="inputJamselesai">End</label>
<!-- <div class="form-label-group"> -->
<input type="time" name="inputJamselesai" id="inputJamselesai" onchange="javascript: hitungjam();" class="form-control" required="required">
<!-- </div> -->
</div>
</div>
</div>
RESULT
start 09:00 AM
end 11:30 AM
the result is NaN.
WHAT EXPECTED RESULT
start at 09:00 AM, end at 11:30 AM, the result is 2,5
Oh FYI, before I write down this question I've done a search and tried many solutions given from StackOverflow but doesn't work on my problem. That's why I'm asking now.
Can anyone here help me to find out the solution? Thank you
Here is couple of things First in order to get the value from the input use val() which was missing. Secondly the output from the input is a string, so use parseInt to convert it to number before doing mathematical operations
Using split to get the numbers from the input since the input will be like 9:00 for 9:00AM or 23:30 for 11:30PM.
function hitungjam() {
var start = $('#inputJammulai').val();
var end = $('#inputJamselesai').val();
let diff = toMins(end) - toMins(start);
let jam = `${Math.floor(diff/60)}:${diff%60}`;
$('#inputSelisih').val(jam);
}
function toMins(time) {
let splitTime = time.split(":");
return (parseInt(splitTime[0], 10) * 60) + parseInt(splitTime[1], 10)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<div class="form-row">
<div class="col-md-4">
<label for="inputJammulai">Start</label>
<!-- <div class="form-label-group"> -->
<input type="time" name="inputJammulai" id="inputJammulai" class="form-control" required="required">
<!-- </div> -->
</div>
<div class="col-md-4">
<label for="inputJamselesai">End</label>
<!-- <div class="form-label-group"> -->
<input type="time" name="inputJamselesai" id="inputJamselesai" onchange="javascript: hitungjam();" class="form-control" required="required">
<!-- </div> -->
</div>
</div>
</div>
<input id='inputSelisih'>
I have done some modifications to your original code so you can get a base working example, I will try to explain some of these:
1) You was not getting the values from your inputs, you need to use .val() for this.
2) You can't make a difference between strings and expect a number as result. Instead of this, I have splited the obtained values from the inputs into hours and minutes. Then we create new Date objects with current time and set the respective hours and minutes to they. Finally, we can use difference within the Date.getTime() of each Date.
3) Math.floor() will return an integer, but you want a number with decimals, so instead of this I use toFixed(1) to get a decimal number (as string) with one digit after the dot.
Base Example:
function hitungjam()
{
var [h1, m1] = $('#inputJammulai').val().split(":");
var [h2, m2] = $('#inputJamselesai').val().split(":");
var start = new Date(), end = new Date();
start.setHours(h1);
start.setMinutes(m1);
end.setHours(h2);
end.setMinutes(m2);
var diff = end.getTime() - start.getTime();
var jam = (diff / 1000.0 / 60 / 60).toFixed(1);
$('#inputSelisih').val(jam);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="time" name="inputJammulai" id="inputJammulai" class="form-control" required="required">
<input type="time" name="inputJamselesai" id="inputJamselesai" onchange="javascript: hitungjam();" class="form-control" required="required">
<label>Difference (hours):<label>
<input type="text" id="inputSelisih">
Is there a way to perform validation on the full date of birth (dd/mm/yyyy) to establish if the user is under 18 years. Most of the tutorials I found only shows me how to do it if the user age (not DOB) is under 18.
By the way I'm also using input type of "date" for my DOB textbox.
HTML
<body>
<header class="v-header container">
<div class="fullscreen-backgorund-Booking">
</div>
<div>
<ul>
<li>Home</li>
<li>McLaren Vale</li>
<li>Barossa</li>
<li>Clare</li>
<li>Online Booking</li>
<div id="mySidenav" class="sidenav">
×
Home
McLaren
Barossa
Clare
Online Booking
</div>
<span id="sidebtn" onclick="openNav()">☰</span>
</ul>
</div>
<div class="header-overlay"></div>
<div class="header-content" style="width: 100%;">
<!-- width... is not working in external css... why?-->
<h1 style="margin-top: -100px;">Online Booking</h1>
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
<input type="text" name="fname" placeholder="Firstname"> Date of Brith
<input type="date" name="DoB" placeholder="Date of Birth">
<input type="text" name="TelNumber" placeholder="Telephone number">
<input type="email" name="email" placeholder="Email"> Date of Tour
<input type="date" name="DoT" placeholder="Date of tour (dd.mm.yyyy)">
<form action="" id="calculate" onsubmit="return false;">
<input type="text" placeholder="Number of Travellers" id="val" name="val" value="" />
<label class="radiolabel">
<input type="radio" name="button" value="100">McLaren</label>
<label class="radiolabel">
<input type="radio" name="button" value="150">Barossa</label>
<label class="radiolabel">
<input type="radio" name="button" value="90">Clare</label>
<div id="result" style="display: block;">
Result:</div>
<input type="submit" id="submit" value="Submit" onclick="endresult(document.forms['myForm'].elements['button']);">
</div>
</form>
</div>
I would first calculate the age and then check if he is over 18. Here is a codesnippet.
var birthday1 = new Date("2015-03-25");
var birthday2 = new Date("1994-03-25");
function isOverEighteen(birthday) {
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs);
var age = Math.abs(ageDate.getUTCFullYear() - 1970);
if(age > 17){
return true;
}else{
return false;
}
}
console.log(isOverEighteen(birthday1));
console.log(isOverEighteen(birthday2));
There are many similar questions, but none seem to have good answers.
Rather than calculating age (which is actually tricker than many expect), you can either add 18 years to the date of birth and see if it's before today, or subtract 18 years from today and see if it's after the date of birth.
// Subtract 18 years from now and see if greater than birth date
function over18(birthDate) {
var now = new Date();
var m = now.getMonth();
now.setFullYear(now.getFullYear() - 18);
// deal with today being 29 Feb
if (m != now.getMonth()) now.setDate(0);
return now > birthDate;
}
// Some tests
var opts = {day: '2-digit', month:'short', year:'numeric'};
[new Date(2000,1,29), // 29 Feb 2000
new Date(2000,0,20), // 20 Jan 2000
new Date(2000,0,19), // 19 Jan 2000
new Date(2000,0,18), // 18 Jan 2000
new Date(1999,0,1) // 1 Jan 1999
].forEach(function(d) {
console.log(d.toLocaleString('en-GB', opts), over18(d));
});
A simple improvement is to allow an optional checkDate that defaults to today and use that instead of now.
I have an html form which allows for a taxi booking, but it shouldn't allow bookings back in time! so the time must be current or in the future.
Here is the form, I use datetime-local.
/* Here is the JavaScript validation for the datetime-local. */
var dateTime = document.getElementById("dateTime").value;
if (dateTime == "" || dateTime == null) {
booking.dateTime.focus();
document.getElementById("dateMessage").innerHTML = "Please select a date AND time, thankyou.";
return valid = false;
} else {
document.getElementById("destinationMessage").innerHTML = "";
}
```
<form id="booking" action="">
<div id="firstNameMessage" class="red"></div>
<span class="red">*</span>First Name:
<input type="text" name="firstName" id="firstName">
<br>
<div id="lastNameMessage" class="red"></div>
<span class="red">*</span>Last Name:
<input type="text" name="lastName" id="lastName">
<br>
<div id="numberMessage" class="red"></div>
<span class="red">*</span>Contact Number:
<input type="text" name="number" id="number">
<br>
<div id="unitMessage" class="red"></div>
Unit Number(optional):
<input type="text" name="unit" id="unit">
<br>
<div id="streetNumberMessage" class="red"></div>
<span class="red">*</span>Street Number:
<input type="text" name="streetNumber" id="streetNumber">
<br>
<div id="streetNameMessage" class="red"></div>
<span class="red">*</span>Street Name:
<input type="text" name="streetName" id="streetName">
<br>
<div id="pickupMessage" class="red"></div>
<span class="red">*</span>Suburb:
<input type="text" name="pickupSuburb" id="pickupSuburb">
<br>
<div id="destinationMessage" class="red"></div>
Destination Suburb<span class="red">*</span>:
<input type="text" name="destinationSuburb" id="destinationSuburb">
<br>
<div id="dateMessage" class="red"></div>
Pick-Up Date and Time<span class="red">*</span>:
<input type="datetime-local" name="dateTime" id="dateTime">
<br>
<br>
<input type="button" value="Submit"
onclick="getData('bookingprocess.php','message', firstName.value, lastName.value, number.value, unit.value, streetNumber.value, streetName.value, pickupSuburb.value, destinationSuburb.value, dateTime.value)" />
<input type="reset" value="Reset">
</form>
How can I make it check for being the current time or in the future? (Basically disabling past entries).
Please use input type = "date" instead of date-time. Probably no more supported by browsers.
Please refer this link
Now to set min date you cn use the following snippet
//Get today's date and split it by "T"
var today = new Date().toISOString().split('T')[0];
document.getElementById("dateTime").setAttribute('min', today);
DEMO
You can just compare dates by > and <. Make sure the dates in the same timezone though.
var dateTimeStr = document.getElementById("dateTime").value;
var dateTime = convertDateToUTC(new Date(dateTimeStr));
var now = new Date();
if (isNaN(date.getTime()) || date <= now) {
booking.dateTime.focus();
document.getElementById("dateMessage").innerHTML = "Please select a date AND time in the future, thankyou.";
return valid = false;
} else {
document.getElementById("destinationMessage").innerHTML = "";
}
function convertDateToUTC(date) {
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}
JS Fiddle
You should use a jquery or bootstrap calendar. It is ideal for this situation. It is also very easy for the user to pick up the date this way.
You have all configuration options in such calendars for e.g. assigning culture, date format, mindate, maxdate etc.
Also keep in mind to pick the date from server and set it as mindate in javascript since the datetime might be wrong on client computer.