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);
}
})
Related
I have a form in which a date/time picker is working fine.
I created JavaScript to calculate the two fields' date difference and show in a third field - named Course Duration.
Somehow I am not able to display the results in the "Course Duration" input Field.
Code:
function GetDays() {
var dropdt = new Date(document.getElementById("course_end_date").value);
var pickdt = new Date(document.getElementById("admission_date").value);
return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}
function cal() {
if (document.getElementById("course_end_date")) {
document.getElementById("course_duration").value = GetDays();
}
}
<input id="admission_date" name="admission_date" placeholder="" type="text" class="form-control" value="" />
<input id="course_end_date" name="course_end_date" placeholder="" type="text" class="form-control" value="" />
<input id="course_duration" name="course_duration" placeholder="" type="text" class="form-control" value="" />
You need something to trigger the cal() function, which currently you don't have.
So I made a demo below which has a "Calculate" button. Enter your dates and then press the button, and it will run the calculation. As long as you enter valid dates, it should work.
For example, if you enter 2018-02-01 and 2018-02-02 it will return 366.
var calcButton = document.getElementById("calculate");
calcButton.addEventListener("click", cal);
function GetDays() {
var dropdt = new Date(document.getElementById("course_end_date").value);
var pickdt = new Date(document.getElementById("admission_date").value);
return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}
function cal() {
if (document.getElementById("course_end_date")) {
document.getElementById("course_duration").value = GetDays();
}
}
<input id="admission_date" name="admission_date" placeholder="" type="text" class="form-control" value="" />
<input id="course_end_date" name="course_end_date" placeholder="" type="text" class="form-control" value="" />
<button id="calculate" type="button">Calculate</button>
<input id="course_duration" name="course_duration" placeholder="" type="text" class="form-control" value="" />
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'm making a calculation of more fields and I would like to get the #price + # price2 automatic sum without any jQuery event.
I've been looking for a variety of tutorials but I just managed to get the sum with the click.
I would like her without the click, how can she do it?
function calcscore() {
score = 0;
$(".calc:checked,#TextBox4").each(function() {
score += Number($(this).val());
});
$("#sum").val(score)
$("#price").text(score.toFixed(2));
}
function add() {
var sum = 0;
$(".test").each(function() {
sum += +this.value;
});
return sum; // an add function shouldn't really "alert"
}
$(document).on("change", ".test", function() {
var sum = 0;
$(".test").each(function() {
sum += +$(this).val();
});
$("#price3").val(sum);
});
$(document).ready(function() {
$(".calc").change(function() {
calcscore();
});
$('#add').click(function() {
$("#price3").text(add().toFixed(2));
});
$("#TextBox1").datepicker({
minDate: 0,
maxDate: '+1Y+6M',
altField: "#arrivo",
altFormat: "DD, d MM, yy",
onSelect: function(dateStr) {
var min = $(this).datepicker('getDate'); // Get selected date
$("#TextBox2").datepicker('option', 'minDate', min || '0'); // Set other min, default to today
}
});
$("#TextBox2").datepicker({
minDate: '0',
maxDate: '+1Y+6M',
altField: "#partenza",
altFormat: "DD, d MM, yy",
onSelect: function(dateStr) {
var max = $(this).datepicker('getDate'); // Get selected date
$('#datepicker').datepicker('option', 'maxDate', max || '+1Y+6M'); // Set other max, default to + 18 months
var start = $("#TextBox1").datepicker("getDate");
var end = $("#TextBox2").datepicker("getDate");
var timeDiff = Math.abs((end - start));
var days = Math.ceil(timeDiff / (1000 * 3600 * 24));
$("#TextBox3").val(days);
if (days == 1) {
parseInt($("#TextBox4").val('10'), 10);
parseInt($("#price2").text('10'), 10);
} else if (days == 0) {
parseInt($("#TextBox4").val('10'), 10);
parseInt($("#price2").text('10'), 10);
$("#TextBox3").val('1');
} else if (days == 2) {
parseInt($("#TextBox4").val('12'), 10);
parseInt($("#price2").text('12'), 10);
} else if (days == 3) {
parseInt($("#TextBox4").val('14'), 10);
parseInt($("#price2").text('14'), 10);
} else if (days == 4) {
parseInt($("#TextBox4").val('16'), 10);
parseInt($("#price2").text('16'), 10);
} else if (days >= 5) {
var y = (days) * 4;
parseInt($("#TextBox4").val(y), 10);
parseInt($("#price2").text(y), 10);
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<form>
<div id="tipo-veicolo">
<input class="calc" type="radio" name="type" value="5"> Macchina
<input class="calc" type="radio" name="type" value="2"> Scooter
<input class="calc" type="radio" name="type" value="10"> Camion
</div>
<div class="variant">
<label>Cambio olio</label>
<input class="calc" type="checkbox" name="check1" id="check1" value="10" />
<label>Cambio gomme</label>
<input class="calc" type="checkbox" name="check1" id="check2" value="2" />
<label>Car valet</label>
<input class="calc" type="checkbox" name="check1" id="check3" value="12" />
</div>
<div id="selezione-data">
<div class="check-in">
<label>Check-In</label>
<input type="text" id="TextBox1" />
</div>
<div class="check-out">
<label>Check-Out</label>
<input type="text" id="TextBox2" />
</div>
<div class="numero-giorni">
<label>Numero Giorni</label>
<input type="text" id="TextBox3" value="0" />
<label>Arrivo</label>
<input type="text" id="arrivo" size="30">
<label>Partenza</label>
<input type="text" id="partenza" size="30">
</div>
</div>
<div class="totale">
<input class="test num1" name="totale" id="TextBox4" value="0" />
<input class="test num2" type="text" name="sum" id="sum" value="0"> Sum: <input type="text" class="sum" readonly="readonly">
</div>
</form>
<p>Total: PHP <span id="price">0</span></p>
<p>Total: PHP <span id="price2">0</span></p>
<p>Total: PHP <span id="price3">0</span></p>
<input id="add" type="button" value="add" />
Thank you and good day
Im not sure if I understand you correctly, but you can't do it without using any events.
You can achive automatic aggregation by using, for example, input event in jQuery.
Here is example of this:
$('.num1, .num2').on('input', function () {
$('.sum').val(parseInt($('.num1').val()) + parseInt($('.num2').val()));
});
Here is jfiddle.
Try this to achieve your goal, place it the end of document.ready event
$(document).ready(function() {
..
..
..
$("input").change(function() { // place it at the bottom of other events, this will listen for all inputs
$("#price3").text(add().toFixed(2)); // after input changes it will calculate
});
});
demo
Hope helps,
I have an input box of type=date. I want it to disable all dates after one week from current date. Suppose current date is 11/07/2017, I want all dates from 18/07/2017 to be disabled. So the user can select only dates within one week from today. I've already disabled the past dates in my code.
function validDate(){
var today = new Date().toISOString().split('T')[0];
document.getElementsByName("date")[0].setAttribute('min', today);
}
<body onload="validDate()">
<div class="form-group">
<p>Date<span>*</span></p>
<input type="date" name="date" id="date" class="form-control input-sm " required />
</div>
</body>
Please see the updated code.
[after how many number of days to be disabled i.e. 6 in this case] * 24 * 60 * 60 * 1000
min and max attributes are used to set the minimum and maximum date for type="date"
function validDate(){
var today = new Date().toISOString().split('T')[0];
var nextWeekDate = new Date(new Date().getTime() + 6 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
document.getElementsByName("date")[0].setAttribute('min', today);
document.getElementsByName("date")[0].setAttribute('max', nextWeekDate)
}
<body onload="validDate()">
<div class="form-group">
<p>Date<span>*</span></p>
<input type="date" name="date" id="date" class="form-control input-sm " required />
</div>
</body>
You can use 'max' to disable the future date:
var nextWeek = new Date();
nextWeek = nextWeek.setDate(nextWeek.getDate() + 1).toISOString().split('T')[0];
document.getElementsByName("date")[0].setAttribute('max', nextWeek);
You can have something like
HTML
<table width="68%" border="0" align="center" cellpadding="0" cellspacing="6">
<tr>
<td align="left" valign="middle" class="search-filter-headings">Start Date:</td>
<td align="left" valign="middle">
<input type="text" name="start_date" id="start_date" class="filter-textfields" placeholder="Start Date"/>
</td>
</tr>
<tr>
<td align="left" valign="middle" class="search-filter-headings">End Date:</td>
<td align="left" valign="middle">
<input type="text" name="end_date" id="end_date" class="filter-textfields" placeholder="End Date"/>
</td>
</tr>
</table>
JAVASCRIPT
$( "#start_date" ).datepicker(
{
maxDate: '0',
beforeShow : function()
{
jQuery( this ).datepicker({ maxDate: 0 });
},
altFormat: "dd/mm/yy",
dateFormat: 'dd/mm/yy'
}
);
$( "#end_date" ).datepicker(
{
maxDate: '7',
beforeShow : function()
{
jQuery( this ).datepicker('option','minDate', jQuery('#start_date').val() );
} ,
altFormat: "dd/mm/yy",
dateFormat: 'dd/mm/yy'
}
);
Working Demo http://jsfiddle.net/X82aC/544/
Let me know if you require any further help
You can use the max attribute of the date picker.
function getInputDateFormat(date) {
return date.toISOString().split('T')[0];
}
function validDate() {
var today = new Date();
var maxDate = new Date();
maxDate.setDate(maxDate.getDate() + 7);
document.getElementsByName("date")[0].setAttribute('min', getInputDateFormat(today));
document.getElementsByName("date")[0].setAttribute('max', getInputDateFormat(maxDate));
}
<body onload="validDate()">
<div class="form-group">
<p>Date<span>*</span></p>
<input type="date" name="date" id="date" class="form-control input-sm " required />
</div>
</body>
You should be able to set the max attribute for the date:
function validDate(){
var today = new Date().toISOString().split('T')[0];
var newDate = today()today.setDate(today.getDate() + 7);
document.getElementsByName("date")[0].setAttribute('min', today);
document.getElementsByName("date")[0].setAttribute('max', newDate);
}
just use php date to pass min and max parameter in input date check below code
<input type="date" name="date" min="<?=date('Y-m-d')?>" max="<?=date('Y-m-d',strtotime(date('Y-m-d').'+7 days'))?>">
to add to #lalit sachdeva's code
I wanted where someone can only select 3 days from today and a max of 10 days from then. So here is the edited code if someone needs + 72 hours and max 10 days.
jQuery(document).ready(function($){
var today = new Date(new Date().getTime() + 3 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
var nextWeekDate = new Date(new Date().getTime() + 10 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
document.getElementsByName("merchant_param3")[0].setAttribute('min', today);
document.getElementsByName("merchant_param3")[0].setAttribute('max', nextWeekDate);
});
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;
} '/>