Below is the code i tried.
From:<input data-dojo-id="myFromDate" type="text" name="fromDate" id="fromDate" value="" data-dojo-type="dijit/form/DateTextBox" required="true" constraints="{ datePattern: 'MM/dd/yyyy'}" onChange="myToDate.constraints.min = arguments[0];"/>
To:<input data-dojo-id="myToDate" type="text" name="toDate" id="toDate" value="" data-dojo-type="dijit/form/DateTextBox" required="true" constraints="{ datePattern: 'MM/dd/yyyy'}" onChange="myFromDate.constraints.max = arguments[0];" />
<input type="submit" value="submit"/>
Please suggest how can i only enable future 90 days once date is selected in fromDate field and past 90 days if i select date in toDate field.
I suggest you to use dojo/date for Date operations and dijit/form/DateTextBox
constraints for adding constraints to the DateTextBox widget.
e.g
<label for="fromDate">From:</label>
<input id="fromDate" data-dojo-type="dijit/form/DateTextBox"
data-dojo-props='type:"text", name:"fromDate", required:true,
onChange:function(){
var fromDate = this.get("value");
var fromDate90 = dojo.date.add(fromDate,"day",90);
//Add min date fromDate.
dijit.byId("toDate").constraints.min = fromDate;
//add max date fromDate + 90 days.
dijit.byId("toDate").constraints.max = fromDate90;
} '/>
<label for="toDate">To:</label>
<input id="toDate" data-dojo-type="dijit/form/DateTextBox"
data-dojo-props='type:"text", name:"toDate", required:true,
onChange:function(){
var toDate = this.get("value");
var toDate90 = dojo.date.add(toDate,"day",-90);
//Add max date toDate.
dijit.byId("fromDate").constraints.max = toDate;
//Add min date toDate - 90 days.
dijit.byId("fromDate").constraints.min = toDate90;
} '/>
Related
Currently, the code I'm using only works with one text box because of the element ID. I tried to duplicate the script with different IDs for different text boxes, only 1 text box would show.
<script>
var todaydate = new Date();
var day = todaydate.getDate();
var month = todaydate.getMonth() + 1;
var year = todaydate.getFullYear();
var datestring = day + "/" + month + "/" + year;
window.onload = function(){
document.getElementById("date").value = datestring;
}
</script>
<input type="text" id="date"/ >
that ?
var datestring = new Date().toLocaleDateString();
// initialize Date to any element with specific ID
document.querySelectorAll('#date1, #date2, #date3, #date4')
.forEach(item => item.value = datestring )
<input type="text" id="date1" ><br>
<input type="text" id="date2" ><br>
<input type="text" id="date3" ><br>
<input type="text" id="date4" ><br>
But it is more easy if they use a same class:
var datestring = new Date().toLocaleDateString();
// initialize Date to any element input with class="inDate"
document.querySelectorAll('input.inDate')
.forEach( item => item.value = datestring )
<input type="text" id="date1" class="inDate" ><br>
<input type="text" id="date2" class="inDate" ><br>
<input type="text" id="date3" class="inDate" ><br>
<input type="text" id="date4" class="inDate" ><br>
the problem is the "total price" is not working.when i pick the "pickup date" and "drop date" it will show the value in the input form. i have to key in the number in "number of days" then the total price will calculate. i need the "total of price" is auto calculate. i have try various event of javascript. here i will attach my code. hope someone will help me. thanks in advance.
function sum() {
var txtFirstNumberValue = document.getElementById('num1').value;
var txtSecondNumberValue = document.getElementById('numdays2').value;
var result = parseInt(txtFirstNumberValue) * parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('num3').value = result;
}
}
function GetDays() {
var dropdt = new Date(document.getElementById("drop_date").value);
var pickdt = new Date(document.getElementById("pick_date").value);
return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}
function cal() {
if (document.getElementById("drop_date")) {
document.getElementById("numdays2").value = GetDays();
}
}
<label for="total">Price per day:</label>
<input type="text" name="price" id="num1" onkeyup="sum();" value="3" readonly>
<div id="pickup_date">
<p><label class="form">Pickup Date:</label>
<input type="date" class="textbox" id="pick_date" name="pickup_date" onchange="cal()" /></p>
</div>
<div id="dropoff_date">
<p><label class="form">Dropoff Date:</label>
<input type="date" class="textbox" id="drop_date" name="dropoff_date" onchange="cal()" /></p>
</div>
<div id="reserve_form">
<div id="numdays"><label class="form">Number of days:</label>
<input type="text" id="numdays2" name="numdays" oninput="sum();" />
<label for="total">Total Price (RM)</label>
<input type="text" name="test" placeholder="Total Price" value="" id="num3">
i expect that the total price can automatically calculate.
You just need to make sure your sum function (or in the example just cal) is being called when your inputs are complete and valid. Since you may want to restrict the user from manually setting the number of days I've demonstrated how you might do this by firing a change event programmatically. It's also current practice to attach events to elements programmatically instead of using the inline HTML5 event notation (e.g. "onchange=foo"), see Why are inline event handler attributes a bad idea in modern semantic HTML?
function setDate(event) {
var days = getDays();
// if the number of days is valid
if (!isNaN(days)) {
var nod = document.getElementById("numdays2");
nod.value = days;
// programmatically setting a value will not fire a change event
nod.dispatchEvent(new Event("change"));
}
}
function getDays() {
// returns NaN if either date does not hold a valid date
var dropdt = new Date(document.getElementById("drop_date").value);
var pickdt = new Date(document.getElementById("pick_date").value);
return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}
function cal() {
var pricePerDay = document.getElementById("pricePerDay").value;
if (0 == (pricePerDay = parseInt(pricePerDay))) { return } // TODO needs to handle decimal values
document.getElementById("total").value = parseInt(document.getElementById("numdays2").value) * pricePerDay;
}
function init() {
document.getElementById("drop_date").addEventListener("change", setDate);
document.getElementById("pick_date").addEventListener("change", setDate);
document.getElementById("numdays2").addEventListener("change", cal);
}
document.addEventListener("DOMContentLoaded", init);
<label for="total">Price per day:</label>
<input type="text" name="price" id="pricePerDay" value="" placeholder="Manually enter a value">
<div id="pickup_date">
<p><label class="form">Pickup Date:</label>
<input type="date" class="textbox" id="pick_date" name="pickup_date" /></p>
</div>
<div id="dropoff_date">
<p><label class="form">Dropoff Date:</label>
<input type="date" class="textbox" id="drop_date" name="dropoff_date" /></p>
</div>
<div id="reserve_form">
<div id="numdays"><label class="form">Number of days:</label>
<!-- numdays2 is readonly to ensure the date pickers are used -->
<input type="text" id="numdays2" name="numdays" readonly placeholder="Select dates above" />
<label for="total">Total Price (RM)</label>
<input id="total" type="text" readonly name="test" placeholder="Total Price" value="" id="num3">
</div>
</div>
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.
I want to display total day in text box automatically if I choose from two dates, but I can not get it. If I don't use Javascript, it works. Datepicker can't work if haven't used Javascript. How can I do that?
This is my script:
<input class="form-control" onchange="cal()" placeholder="Choose Date " type="text" id="example1" name="startdate" required="required" "/>
<input class="form-control" onchange="cal()" placeholder="Choose Date " type="text" id="example2" name="enddate" required="required" disabled="disabled" "/>
<input class="form-control" type="text" id="numdays2" name="total_leave"/>
This is java script:
<!--calendar Java script -->
<script type="text/javascript">
$(document).ready(function () {
$('#example1').datePicker({
format: "yyyy-mm-dd"
});
});
</script>
<!-- Datepicker -->
<script type="text/javascript">
$(document).ready(function () {
$('#example2').datePicker({
format: "yyyy-mm-dd"
});
});
</script>
<!-- calculate leave total day -->
<script type="text/javascript">
function GetDays(){
var dropdt = new Date(document.getElementById("example2").value);
var pickdt = new Date(document.getElementById("example1").value);
return parseInt((dropdt -(pickdt)) / (24 * 3600 * 1000))+1|| parseInt(1);
}
function cal(){
if(document.getElementById("example1")){
document.getElementById("numdays2").value=GetDays();
}
}
</script>
There are quite a few bits in your code that need changing / fixing, so here is a working example based on your original code.
<input class="form-control" placeholder="Choose Date " type="text" id="example1" name="startdate" required="required" />
<input class="form-control" placeholder="Choose Date " type="text" id="example2" name="enddate" required="required" />
<input class="form-control" type="text" id="numdays2" name="total_leave"/>
$(document).ready(function(){
$('#example1').datepicker({
format: "yyyy-mm-dd",
onSelect: function(){
cal()
}
});
$('#example2').datepicker({
format: "yyyy-mm-dd",
onSelect: function(){
cal()
}
});
});
function GetDays(){
var dropdt = new Date(document.getElementById("example2").value);
var pickdt = new Date(document.getElementById("example1").value);
return parseInt((dropdt -(pickdt)) / (24 * 3600 * 1000))+1|| parseInt(1);
}
function cal(){
if(document.getElementById("example1")){
document.getElementById("numdays2").value=GetDays();
}
}
Working Demo
changeDate event is triggered every time the date is selected or changed
DatePicker(Events)
HTML
<input placeholder="Start Date " type="text" id="StartDate" />
<input placeholder="End Date " type="text" id="EndDate" />
<input type="text" id="datediff" />
JS
$('#StartDate,#EndDate').datepicker({
format: "yyyy-mm-dd",
autoclose: true,
});
$('#StartDate,#EndDate').datepicker().on('changeDate', function () {
if ($('#StartDate').val() != '' && $('#EndDate').val() != '') {
var date1 = new Date($('#StartDate').val());
var date2 = new Date($('#EndDate').val());
var timeDiff = date2.getTime() - date1.getTime();
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
$('#datediff').val(diffDays);
}
})
I have this case:
two datepickers,and two values, and a select (HTML terms).
Select Start
<input type="date" name ="datepicker_start" id="datepicker" value="" class="datepicker" size="20" />
<br>
Select End
<input type="date" name ="datepicker_end" id="datepicker2" value="" class="datepicker" size="20" />
<br>
Balance 1
<input type="number" name="tleave" id="Total" value="20" readonly="true" size="10" />
<br>
Balance 2
<input type="number" name="tleave2" id="Total2" value="2" readonly="true" size="10" />
<br>
<select onchange="checkdate();" name="LeaveType">
<option value="0"> select balance</option>
<option value="1"> Balance 1</option>
<option value="2"> Balance 2</option>
<option value="3"> Balance 3</option>
</select>
I started putting up a code that checks the input dates and compare it to a value depending on the selection of select option.
function checkdate() {
var start = new Date( $('#datepicker').val() ).getTime(),
end = new Date( $('#datepicker2').val() ).getTime();
diff = ((end - start) / 86400000) ;
//1000 * 60 * 60 * 24 = 1 day = 86400000
if ($('#element option[value="1"]').attr("selected", "selected"))
{
if( diff > $('#Total').val())
{
alert( diff+ " days of balance 1 more than the available" );
}
}
if ($('#element option[value="2"]').attr("selected", "selected"))
{
if( diff > $('#Total2').val())
{
alert( diff+ " days of balance 2 more than the available" );
}
}
};
I.E. let consider that the user have two different balances,so after he selects the duration,based on which balance type he wants,the function should returns a pop-up if the balance is less the requested.
the current issue is that : the function is not separating on changing option.(you will understand better if you check the code below)
or here's my JSFiddle
You could make a shorter version of your code if you change the id of #Total to #Total1 and use this:
function checkdate() {
var start = new Date( $('#datepicker').val() ).getTime(),
end = new Date( $('#datepicker2').val() ).getTime();
var diff = ((end - start) / 86400000) ;
var val = $('#LeaveType').val();
if( diff > $('#Total'+val).val()){
alert( diff+ " days of balance "+val+" more than the available" );
}
};
I managed to fixed it.
I added ID to the select
<select onchange="checkdate();" name="LeaveType" id="LeaveType">
the issue was on these lines :
if ($('#element option[value="1"]').attr("selected", "selected"))
and
if ($('#element option[value="2"]').attr("selected", "selected"))
i changed them to:
var option = document.getElementById("LeaveType").value;
if (option =='1')
AND
if (option =='2')
Now function is working great.
Thank you..