Increase the date and assign as a max in date field - javascript

I'm using javascript to get the value of form input field with getElementById("myTextInputID")
How can I increase the date by 21 days (3 weeks) and assign this new date as a max in the date field with name end_date ?
What I have tried with new Date() and addDays(21) is not working for me.
<form action ="form_page.php" method="post">
<div id="standardPanel">*Task / Person: <input type="text" name="product" required ></div>
<div id="standardPanel">*Description: <input type="text" name="customer" required ></div>
<div id="standardPanel">*Date: <input id="myTextInputID" type="date" name="manufacture_one" required ></div>
<p class="flip" onclick="showEndDate()">Click to add End Date</p>
<div id="panel">
End Date: (holidays only) <input type="date" name="end_date">
</div>
<div><input id="submit" name="action" type="submit" value="submit"/></div>
</form>
<script>
function showEndDate() {
var inputValue = document.getElementById("myTextInputID").value;
if(inputValue != "") {
document.getElementById("panel").style.display = "block";
} else {
alert("Date cannot be blank");
}
var inputValue = new Date(document.getElementById("myTextInputID").value);
inputValue.addDays(21);
document.getElementsByName('end_date')[0].setAttribute("max", inputValue);
}
</script>```

The addDays method doesn't exist. You need to use the setDate() method.
let dateInput = document.getElementById("dateInput");
dateInput.addEventListener("change", () => {
console.log("eventWorking");
var inputValue = dateInput.value;
var inputDate = new Date(inputValue);
console.log(inputDate);
// Adding 21 days using setDate
inputDate.setDate(inputDate.getDate() + 21);
console.log(inputDate);
})
Date: <input id="dateInput" type="date" name="manufacture_one" required >
In summary you can just replace the line inputValue.addDays(21); with inputValue.setDate(inputValue.getDate() + 21);
But avoid using the same var name two times in the same method ! As it will be bring you problems and it is easy to find two differents name

You use the setDate method to add the desired amount of days to an existing date object and, for simplicity in outputting to the end_date field rather than simply use value you can use valueAsDate as below.
Incidentally ID attributes MUST be unique and in most cases are not really required as identification of DOM elements can be done in other ways such as querySelector. Also perhaps worth noting is that the use of inline event handlers is not considered best practise nowadays - externally registered event handlers are much cleaner '-)
document.querySelector('p.flip').addEventListener('click',function(e){
let manufacture_date=this.parentNode.querySelector('[name="manufacture_one"]');
let end_date=this.parentNode.querySelector('[name="end_date"]');
if( manufacture_date.value=='' ){
alert('Date cannot be blank');
return false;
}
let mdate=new Date( manufacture_date.value );
let ndate=new Date( mdate.setDate( mdate.getDate() + 21 ) );
end_date.valueAsDate=ndate;
});
<form action="form_page.php" method="post">
<div>*Task / Person: <input type="text" name="product" required /></div>
<div>*Description: <input type="text" name="customer" required /></div>
<div>*Date: <input type="date" name="manufacture_one" required /></div>
<p class="flip">Click to add End Date</p>
<div id="panel">End Date: (holidays only) <input type="date" name="end_date"></div>
<input type="submit" />
</form>
Or, an alternative that uses a change event listener bound to the manufacture_one date input field so that the user does not need to click the "click here to..." link to calculate the new date.
document.querySelector('[name="manufacture_one"]').addEventListener('change',function(e){
if( this.value=='' ){
alert('Date cannot be blank');
return false;
}
let mdate=new Date( this.value );
document.forms.dates.end_date.valueAsDate=new Date( mdate.setDate( mdate.getDate() + 21 ) );
});
<form name='dates' action="form_page.php" method="post">
<div>*Task / Person: <input type="text" name="product" required /></div>
<div>*Description: <input type="text" name="customer" required /></div>
<div>*Date: <input type="date" name="manufacture_one" required /></div>
<div id="panel">End Date: (holidays only) <input type="date" name="end_date"></div>
<input type="submit" />
</form>

Related

addEventListener for input not working anymore after validation error is thrown

The problem
I use a form on a webpage where users fill in all sorts of details. There are 3 fields which generate the input for another field. That field gets generated like this: Firstname + Lastname + Date of birth. However, when a validation error is thrown on the form and the page reloads, the generated input isn't the expected format anymore. Only the Date of birth is then in that input.
It looks like it isn't initializing the Firstname + Lastname field anymore after a validation error is thrown on the page. Any suggestions on how to make it so that the fields gets initialized constantly? Or is there maybe a better way to handle this?
This is the code I use for the generated input
window.onload = function() {
let studentNoField = document.getElementById('input_7_9');
let enteredDetails = {
name: '',
lastname: '',
date: ''
};
/* set value in the third input: Studentnummer */
function generateInput() {
let studentNumber = Object.values(enteredDetails).join('').toLowerCase();
studentNoField.value = studentNumber;
}
/* event listener for first input: Voornaam */
document.getElementById('input_7_1').addEventListener('input', function(event) {
enteredDetails.name = event.target.value.replace(/\s/g, '').slice(0, 8);
generateInput();
});
/* event listener for second input: Achternaam */
document.getElementById('input_7_25').addEventListener('input', function(event) {
enteredDetails.lastname = event.target.value.replace(/\s/g, '').slice(0, 8);
generateInput();
});
/* event listener for second input: Date */
document.getElementById('input_7_3').addEventListener('input', function(event) {
enteredDetails.date = event.target.value.replace(/-/g, '').slice(0, 4);
generateInput();
});
/* Get selected training and format it properly for the PDF */
jQuery('#input_7_23').change(function(e) {
var optionChange = jQuery('#input_7_23 option:selected').text().toUpperCase();
jQuery('#input_7_58').val(optionChange);
});
}
<html>
<body>
<form method="post" enctype="multipart/form-data" id="gform_7" action="/budget/" _lpchecked="1">
<div>
<div id="gform_fields_7">
<div id="field_7_9">
<label for="input_7_9">Studentnummer
<input name="input_9" id="input_7_9" type="text" value="" maxlength="20" aria-required="true" aria-invalid="false">
</div>
</div>
<div id="field_7_1">
<label for="input_7_1">Voornaam</label>
<div><input name="input_1" id="input_7_1" type="text" value="" aria-required="true" aria-invalid="false"> </div>
</div>
<div id="field_7_25">
<label for="input_7_25">Achternaam</label>
<div><input name="input_25" id="input_7_25" type="text" value="" aria-required="true" aria-invalid="false"> </div>
</div>
<div id="field_7_3">
<label for="input_7_3">Geboortedatum</label>
<div>
<input name="input_3" id="input_7_3" type="text" value="" placeholder="dd-mm-yyyy" aria-describedby="input_7_3_date_format" aria-invalid="false" aria-required="true">
<span id="input_7_3_date_format">DD dash MM dash JJJJ</span>
</div>
</div>
</div>
</div>
<div>
<input type="submit" id="gform_submit_button_7" value="Versturen" onclick="if(window["gf_submitting_7"]){return false;} window["gf_submitting_7"]=true; " onkeypress="if( event.keyCode == 13 ){ if(window["gf_submitting_7"]){return false;} window["gf_submitting_7"]=true; jQuery("#gform_7").trigger("submit",[true]); }">
</div>
</form>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Any help or suggestions is appreciated.
There were a few non-existing ids referenced in your code. In the following snippet I have tried to "correct" these errors, but I also went further: I removed all repetitions, thereby following the DRY principle "Don't repeat yourself". The "input"-event listener now works for all elements of the inps array. There is, however one differentiation: the first two elements are limited to 8 characters while the date is limited to 4: .slice(0,i<2?8:4).
const [stNr, ...inps]=[9, 1, 25, 3].map(n=> document.getElementById(`input_7_${n}`));
inps.forEach(inp=>inp.addEventListener("input",()=>
stNr.value=inps.map((el,i)=>
el.value.replace(/[\s-]/g,"").slice(0,i<2?8:4).toLowerCase()
).join(""))
)
<form method="post" enctype="multipart/form-data" id="gform_7" action="/budget/" _lpchecked="1">
<div>
<div id="gform_fields_7">
<div id="field_7_9">
<label for="input_7_9">Studentnummer</label>
<input name="input_9" id="input_7_9" type="text" value="" maxlength="20" aria-required="true" aria-invalid="false">
</div>
</div>
<div id="field_7_1">
<label for="input_7_1">Voornaam</label>
<div><input name="input_1" id="input_7_1" type="text" value="" aria-required="true" aria-invalid="false"> </div>
</div>
<div id="field_7_25">
<label for="input_7_25">Achternaam</label>
<div><input name="input_25" id="input_7_25" type="text" value="" aria-required="true" aria-invalid="false"> </div>
</div>
<div id="field_7_3">
<label for="input_7_3">Geboortedatum</label>
<div>
<input name="input_3" id="input_7_3" type="text" value="" placeholder="dd-mm-yyyy" aria-describedby="input_7_3_date_format" aria-invalid="false" aria-required="true">
<span id="input_7_3_date_format">DD dash MM dash JJJJ</span>
</div>
</div>
</div>
</div>
<div>
<input type="submit" id="gform_submit_button_7" value="Versturen">
</div>
</form>
I removed your jQuery statements at the end of your script, as they referred to non-existent ids. These statements can definitely also be re-written in Vanilla JS, if necessary.
And, as #CherryDT already mentioned: there is no validation code visible here. If it happens on the server then it is the server's responsibility to produce a suitable response that allows the client to render the page with the previously (possibly annotated) content.

Display text / Number in the Input based on selected days and weekends

I want to display the amount in the textbox based on the date selected.For weekdays amount is 200 on sundays amount is 500. How can I do it in jquery? Whether it is possible to do?
How can I do it in jquery?
<input type="date" name="mass_date" id="txtDate" required="required" class="col-md-12" />
<input type="text" class="form-control" id="slDay" name="amount" />
Use getDay. Add a event listener to to input change then each time the input changes create a new Date and then use the getDay function that returns the day number (0 for Sunday).
Then you can put a conditional statement to change the form-control selector.
$(function() {
$("#txtDate").change(function() {
var selDate = new Date(this.value);
if (selDate.getDay() == 0) { //If sunday, can change your logic here
$(".form-control").val(5000);
} else {
$(".form-control").val(2000);
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date" name="mass_date" id="txtDate" required="required" class="col-md-12" />
<input type="text" class="form-control" id="slDay" name="amount" />
A simple version
$(function() {
$("#txtDate").change(function() {
var dow = new Date(this.value).getDay();
$(".form-control").val(dow === 1 || dow ===6 ? 2000 : 5000);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date" name="mass_date" id="txtDate" required="required" class="col-md-12" />
<input type="text" class="form-control" id="slDay" name="amount" />

How to check datetime-local input field is not less than other datetime-local field

I am creating a form, where i am using datetime-local for 2 input fields - StartDate and EndDate.
How can I ensure EndDate is not less than StartDate. I wrote below JS, but it is not working on selecting date / or even onclick on submit button of the page.
Please advise, and thanks for taking your time to read through this :)
function checkDate() {
var dateString = document.getElementById('StartDate').value;
var dateString2 = document.getElementById('EndDate').value;
var DateStart = new Date(dateString);
var DateEnd = new Date(dateString2);
if (DateEnd > DateStart) {
alert("End date cannot be less than Start date.");
return false;
}
return true;
}
<input type="datetime-local" class="form-control name_list" name="StartDate" id="StartDate" required="required" onclick="checkDate()" />
</div>
<div class="col-lg-1 mb-0">
<h6>Deployment End *</h6>
</div>
<div class="col-lg-3 mb-0">
<input type="datetime-local" class="form-control name_list" name="EndDate" id="EndDate" required="required" onclick="checkDate()" />
</div>
Using the click event handler will only activate when you click on the form, firing when you do not have any of the useful information. The alternative would be 'onchange' which will fire when you complete the input.
<input type="datetime-local" class="form-control name_list" name="StartDate" id="StartDate" required="required" onchange="checkDate()" />
<input type="datetime-local" class="form-control name_list" name="EndDate" id="EndDate" required="required" onchange="checkDate()" />
If you want to make sure your end date is in the future compared to your start date you need to swap the comparison operator.
if (DateEnd < DateStart) {
alert("End date cannot be less than Start date.");
return false;
}
return true;

Second date greater than first date in javascript

I have 2 date inputs i would like the min of checkout to be set to the value of checkin.
Check In
<input type="date" id="checkIn" name="checkIn">
Check out
<input type="date" id="checkOut" min="" name="checkOut">
The idea is to have the check out date to be greater than the check in date after the user enters the first date.
I have tried using a something like this (works on numbers but not dates)
function updatedate() {
var firstdate = document.getElementById("checkIn").value;
document.getElementById("checkOut").min = firstdate;
}
Using onclick for the input.
Any suggestions would be great thank you.
Try this
<label>Check In</label>
<input type="date" id="checkIn" name="checkIn" onchange="updatedate();">
<label>Check out</label>
<input type="date" id="checkOut" min="" name="checkOut">
-
function updatedate() {
var firstdate = document.getElementById("checkIn").value;
document.getElementById("checkOut").value = "";
document.getElementById("checkOut").setAttribute("min",firstdate);
}
Your code works for setting the minimum. Use the 1st input change event to update the 2nd input minimum, instead of click:
var checkIn = document.getElementById('checkIn');
var checkOut = document.getElementById('checkOut');
checkIn.addEventListener('change', updatedate);
function updatedate() {
var firstdate = checkIn.value;
checkOut.min = firstdate;
}
#checkOut:invalid {
color: red;
}
<div>When the checkOut is less than the checkIn, the checkout color will change to red</div>
<label>Check in</lable>
<input type="date" id="checkIn" name="checkIn">
<label>Check out</lable>
<input type="date" id="checkOut" min="" name="checkOut">

Why is my AngularJS ngModel binding to the time inputs, but not binding to the date inputs?

I'm trying to bind an input of type date to a model. I'm able to bind to time fields, but I'm having trouble with date fields. The HTML:
<div ng-app ng-controller="HistoryCtrl">
<input type="date" nm-model="startDate" />
<input type="time" ng-model="startTime" />
<input type="date" nm-model="endDate" />
<input type="time" ng-model="endTime" />
<button ng-click="updateForm()">Update</button>
</div>
This is my controller (simplified):
function HistoryCtrl($scope) {
$scope.result = {
result: 'success',
start: '2013-11-23 03:00:00',
end: '2013-11-24 16:30:00',
delta: 0.05681799352169
};
$scope.updateForm = function () {
$scope.updateTimespan($scope.result.start, $scope.result.end);
};
$scope.updateTimespan = function (start, end) {
$scope.startDate = start.split(" ")[0];
$scope.startTime = start.split(" ")[1];
$scope.endDate = end.split(" ")[0];
$scope.endTime = end.split(" ")[1];
}
}
Here's a fiddle: http://jsfiddle.net/t3m6r/2/
I'm using Google Chrome 31.0.1650.57 for Mac. When I click the "Update" button, the time fields update but the date fields do not. Why? Am I doing it wrong?
You are using ng-model but type wrongs, "nm-model".
<input type="date" ng-model="startDate" />
<input type="time" ng-model="startTime" />
<input type="date" ng-model="endDate" />
<input type="time" ng-model="endTime" />
See JS Fiddle

Categories