HTML:
<p id="bon_date" class="inline" style="color:#0000ff;" contenteditable="true" onchange="add7day()"> enter date </p>
javascript:
function add7day() {
var str = document.getElementById(#bon_date).value;
var startdate = str.split("/");
var month = parseInt(stardate[0], 10);
var day = parseInt(stardate[1], 10);
var o_month = parseInt(stardate[0], 10);
var o_day = parseInt(stardate[1], 10);
if (month == 1 | month == 3 | month == 5 | month == 7 | month == 8 | month == 10 | month == 12) {
if ((day + 7) > 31) {
month = month + 1;
day = day + 7 - 31;
} else {
day = day + 7;
}
document.getElementById(#bon_date).innerHTML = o_month + "/" + o_day + "~" + month + "/" + day;
} else {
if ((day + 7) > 30) {
month = month + 1;
day = day + 7 - 30;
} else {
day = day + 7;
}
document.getElementById(#bon_date).innerHTML = o_month + "/" + o_day + "~" + month + "/" + day;
}
I can get the string from input type field but I can`t get it from contenteditable field.
and when it runs to var month = parseInt(stardate[0],10); I get errors like:
stardate[0] is not define..
I want input a date by manual and gets the date after 7 days.
Any ideas?
Okay, where to begin.
I'm not going to question the use of a contenteditable element instead of an input type="text" or input type="date" element, I'm just going to fix your JavaScript.
Elements with contenteditable are not converted to input elements or textareas, so they do not have a value property, but they do have a textContent because they're otherwise normal HTML nodes which can have text nodes.
Elements with contenteditable also do not emit an onchange or change event when their text content is edited. You could listen for the input event, but that would break your code, because your function would constantly amend the element's contents every time the user pressed a key—making it practically unusable.
The next best thing to the onchange event is the onblur/blur event, so we'll use that. This means when the user focuses off the event, i.e. clicks outside it (or presses the tab key etc) the function will fire.
stardate[0] comes back as undefined because you didn't define a variable called stardate, you defined startdate. Similarly, none of the code works at all without getting the bon_date element, which in this case would be done by fixing your code so document.getElementById() is given a parameter 'bon_date' (not '#bon_date', because document.getElementById does not use CSS selectors).
// Store the element in a variable so we don't have to keep writing this crap out.
var bd = document.getElementById('bon_date');
// Listen for the blur event by adding an event listener in JavaScript.
// You could also use an 'onblur=' attribute on the element in question.
bd.addEventListener('blur', add7day, false);
function add7day() {
// Get the element's text content.
var str = bd.textContent;
// You could just say startdate = bd.textContent.split("/") and leave out out the str variable.
var startdate = str.split("/");
var month = parseInt(startdate[0], 10);
var day = parseInt(startdate[1], 10);
var o_month = parseInt(startdate[0], 10);
var o_day = parseInt(startdate[1], 10);
if (month == 1 | month == 3 | month == 5 | month == 7 | month == 8 | month == 10 | month == 12) {
if ((day + 7) > 31) {
month = month + 1;
day = day + 7 - 31;
} else {
day = day + 7;
}
// no need to use innerHTML, just amend the textContent again
bd.textContent = o_month + "/" + o_day + "~" + month + "/" + day;
} else {
if ((day + 7) > 30) {
month = month + 1;
day = day + 7 - 30;
} else {
day = day + 7;
}
bd.textContent = o_month + "/" + o_day + "~" + month + "/" + day;
}
}
<p id="bon_date" class="inline" style="color:#0000ff;" contenteditable="true"> Enter date (MM/DD) </p>
That gets your code working. Sort of. You should think about validating user input to make sure it's a valid date (not the 1000th day of a 50th month) etc. Moment.js is a very handy JavaScript library to use when dealing with dates and times.
Related
I have set the date type input to display calendar with date not less than 18 years to avoid user choosing date that is less than 18 years old. But the problem is the user still able to manually type in a wrong date. Is there a way to show an alert message and empty the input when a date less than 18 years is typed in?
$(function(){
var dtToday = new Date();
var month = dtToday.getMonth() + 1;// jan=0; feb=1 .......
var day = dtToday.getDate();
var year = dtToday.getFullYear() - 18;
if(month < 10)
month = '0' + month.toString();
if(day < 10)
day = '0' + day.toString();
var minDate = year + '-' + month + '-' + day;
var maxDate = year + '-' + month + '-' + day;
$('#emp_dob').attr('max', maxDate);
});
<div class="form-group">
<label>Date of Birth</label>
<input type="date" name="emp_dob" id="emp_dob" class="form-control">
</div>
I infer you are using jquery, so it's pretty easy, you need to do the following:
Define in which HTML tag you want to show this alert box.
Make the checkup.
Print the message.
if (year < 18) {
$('.error-div').html("You can't choose less than 18 years");
}
You can also use $.append.
Check the following links:
https://api.jquery.com/html/
https://api.jquery.com/append/#append-content-content
https://api.jquery.com/text/#text
Use the one that better fits your problem.
You already have the date picker not allowing a selection of a Date less than 18 years from today's date. So IMHO it doesn't seem feasible to have an alert for a selection that isn't possible.
But, if you would like to do that, you must create a new condition like so:
if ( year < 18 ) {
alert("You must be 18 years of age");
}
$(function(){
var dtToday = new Date();
var month = dtToday.getMonth() + 1;// jan=0; feb=1 .......
var day = dtToday.getDate();
var year = dtToday.getFullYear() - 18;
if(month < 10)
month = '0' + month.toString();
if(day < 10)
day = '0' + day.toString();
var minDate = year + '-' + month + '-' + day;
var maxDate = year + '-' + month + '-' + day;
$('#emp_dob').attr('max', maxDate);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" referrerpolicy="no-referrer"></script>
<div class="form-group">
<label>Date of Birth</label>
<input type="date" name="emp_dob" id="emp_dob" class="form-control">
</div>
Every HTML <input> element fires a series of events. For instance if you add an change event listener to your date input, it would fire as soon as the user inputs something. So the basic idea is we catch if the user entered something and compare the input to a target date - in your case sometime before 18 years. The problem with this is that the event would fire every time the user changes a single number, not just once if the entire date is set. What we need to do instead is waiting for a press of the return key, as it's used to actually set the chosen date.
Inside the callback function we can compare the date to the target date and act accordingly - e.g. display an alert box.
Here's an example:
let minDate = new Date("2003-07-21");
document.getElementById("emp_dob").addEventListener("keyup", function(e) {
if (e.key == "Enter") {
if (new Date(e.target.value) > minDate) {
alert("Wrong date!");
}
}
});
<div class="form-group">
<label>Date of Birth</label>
<input type="date" name="emp_dob" id="emp_dob" class="form-control">
</div>
First of all, this forum has been outstanding at helping me learn the limited scripting I do understand so thanks to everyone who contributes.
I have been using the following script on my website to generate a dropdown menu of months/years for a form:
<script>
function CreateMonthDropDown(){
var arrMonthName = new Array();
arrMonthName =
["January","February","March","April","May","June","July","August","September","October","November","December"];
var ThisDate = new Date();
var ThisMonth = ThisDate.getMonth();
var ThisYear = ThisDate.getFullYear();
var tmpMonthYear;
var tmpMonthYearName;
document.write(" <option value=\"\">Any Date</option>");
for ( i = 0; i < 36; i++) {
if ( ThisMonth == 12 ) {
ThisMonth = ThisMonth - 12;
ThisYear = ThisYear + 1;
}
if ( (ThisMonth + 1) < 10 ) {
tmpMonthYear = '0' + (ThisMonth + 1) + '*' + ThisYear + '*';
} else {
tmpMonthYear = (ThisMonth + 1) + '*' + ThisYear + '*';
}
tmpMonthYearName = arrMonthName[ThisMonth] + ' ' + ThisYear;
document.write(" <option value=\"" + tmpMonthYear + "\">" + tmpMonthYearName + "</option>");
ThisMonth = ThisMonth + 1;
}
}
</script>
<font size="1">Travel Date:</font><br><select name="srchStartTravDate">
<script>CreateMonthDropDown();</script></select>
This is great for generating month/year and removing outdated options. However, an API search I use has recently changed their values. Here's what I need:
I need the display to remain the same to the user - January 2018, February 2018 etc.
But I need the value passed through on the form in the following format:
Month needs to be reflected in a two digit number 01, 02 etc. with a * on the end
Year needs to be reflected in a four digit number 2018, 2019 etc. with a * at end
All entries need to be appended with &DateRangeType=4
So for example, May 2018 would pass the value of: 05*2018*&DateRangeType=4
I've searched and searched for a script that will do this and can't find it or figure out how to adapt it to make this work. Is it possible? Any advice would be greatly appreciate. Thanks in advance.
This is my code and I want to add two days from the current date to the value of a hidden input. If I borrow now, this results in a waiting period of two days. It will be better if I borrow on Friday; Saturdays and Sundays will not count so the waiting period ends on Monday, four days later.
<input type="hidden" name="due_date" id="sd" maxlength="10" style="border: 3px double #CCCCCC;" required/>
You can use JavaScript to add 2 days and For Friday(5) add 4 days to skip Saturday And Sunday plus 2 days:
var currentDate = new Date();
//Checking If Current day is Friday
if(currentDate.getDay() == 5) {
var numberOfDaysToAdd = 4; //Adding 4 to skip sat. & sun. if Friday
} else {
var numberOfDaysToAdd = 2; //Adding 2 days if not Friday
}
currentDate.setDate(currentDate.getDate() + numberOfDaysToAdd);
//Formatting to dd/mm/yyyy :
var dd = currentDate.getDate();
var mm = currentDate.getMonth() + 1;
var y = currentDate.getFullYear();
var someFormattedDate = dd + '/'+ mm + '/'+ y;
// Displaying Fromatted Date
document.getElementById("display").innerHTML = someFormattedDate;
<div id="display"></div>
It has been assumed that nothing is Borrowed on Saturday And Sunday.
The code creates an array of objects referring to the days of the week as well as a Date object oDate used to retrieve the current date information. If the day of the week is not Friday, then user is advised to wait till Friday.
The hidden input "due_date" has its value set to two days from the current date unless that day is Friday in which case the due date becomes 4 days later, to skip the weekend and add the usual 2 days to the waiting period. If the hidden input were part of a form, once it is submitted, and the data validated, assuming submission by POST, one could use variable $_POST["due_date"] in an INSERT query to store that value in a database, making sure to use either mysqli_real_escape_string() or PDO and bound parameters.
Note: I altered the HTML so that both the NAME and ID attributes of the hidden input are both set to "due_date".
var d = document;
d.g = d.getElementById;
var arrDaysOfWeek = {"Sunday":0,"Monday":1,"Tuesday":2,"Wednesday":3,"Thursday":4,"Friday":5,"Saturday":6};
var arrWkDayNames = Object.keys( arrDaysOfWeek );
var oDate = new Date();
var currDay = oDate.getDay();
var md = oDate.getDate();
var mm = oDate.getMonth() + 1;
var y = oDate.getFullYear();
var waitPeriod = 2; // default
var daysTillFriday = (currDay == 0)? arrDaysOfWeek["Friday"]
: arrDaysOfWeek["Friday"] - currDay;
if (currDay == arrDaysOfWeek["Saturday"]) {
daysTillFriday = arrWeekDayNames.length + arrDaysOfWeek["Friday"] - currDay;
}
var mess = "";
if (currDay != arrDaysOfWeek["Friday"] ) {
mess = "\nYou should wait to borrow on Friday, i.e. " + daysTillFriday + " days from today.";
}
if( currDay + 2 != arrDaysOfWeek["Friday"] ) {
daysTillFriday = arrDaysOfWeek["Friday"] - currDay - 2;
mess += "\nSo, best not even in two days. Just wait till Friday which will be in " + daysTillFriday + " days from two days from now.";
}
waitPeriod = (currDay == arrDaysOfWeek["Friday"] )
? 4 //skip sat. & sun. plus 2
: 2; // usual wait period
oDate.setDate(md + waitPeriod);
mess += "\nTo proceed know that the happening date is " + oDate;
//USA date style ...
var date_parts = [ mm, md, y ];
mess += "\nToday is " + arrWkDayNames[ currDay ] + ", " + date_parts.join("/");
d.g("display").textContent = mess;
d.g("due_date").value = oDate;
console.log( "Hidden input due date value: " + d.g("due_date").value );
<div id="display"></div>
<input type="hidden" name="due_date" id="due_date" maxlength="10" style="border: 3px double #CCCCCC;" required/>
You can use JavaScript, no jQuery required:
var someDate = new Date();
var numberOfDaysToAdd = 2;
someDate.setDate(someDate.getDate() + numberOfDaysToAdd);
Formatting to dd/mm/yyyy :
var dd = someDate.getDate();
var mm = someDate.getMonth() + 1;
var y = someDate.getFullYear();
var someFormattedDate = dd + '/'+ mm + '/'+ y;
answer from - How to add number of days to today's date?
You can do it in php
echo date('Y-m-d', strtotime("+2 days"));
Answer From - Add number of days to a date
I have inherited a form that has some existing JavaScript that creates a new date + 3 months from today's date.
var monthAway = new Date(new Date);
var day =monthAway.getDate();
var month =monthAway.getMonth() + 3;
var year =monthAway.getFullYear();
$('#Date_for_Second_Store_Access_to_Expire').val(day + "/" + month + "/" + year);
<p><input id="Date_for_Second_Store_Access_to_Expire" type="hidden" name="Date_for_Second_Store_Access_to_Expire" class="required" /></p>
Issue is that if today's date is in October, November or December new date month will be 13, 14 or 15 rather than updating the to 1, 2 or 3 and then updating the year, e.g. 5/11/2014 is 05/14/2014 rather than 05/02/2015.
Any ideas?
Try this:
var x = 3; //or whatever offset
var CurrentDate = new Date();
CurrentDate.setMonth(CurrentDate.getMonth() + x);
alert(CurrentDate);
Add 3 months to monthAway variable using setMonth method as below
monthAway.setMonth(monthAway.getMonth() + 3);
then simply use the modified monthAway to display the expiration date. Please note that getMonth() Method will return 0-11 where 0 is January, 1 is February, ... , 11 is December, so you need to do this to display the correct month
var month = monthAway.getMonth() + 1;
This is the complete modified code, the value of #Date_for_Second_Store_Access_to_Expire would be 5/2/2015 assuming the code is executed today (5/11/2014).
var monthAway = new Date(new Date);
monthAway.setMonth(monthAway.getMonth() + 3); // add 3 months to monthAway
var day = monthAway.getDate();
var month = monthAway.getMonth() + 1; // add 1 because .getMonth returns zero based month
var year = monthAway.getFullYear();
$('#Date_for_Second_Store_Access_to_Expire').val(day + "/" + month + "/" + year);
<p><input id="Date_for_Second_Store_Access_to_Expire" type="hidden" name="Date_for_Second_Store_Access_to_Expire" class="required" /></p>
This is the JSFiddle that shows the value of day + "/" + month + "/" + year from the above code: http://jsfiddle.net/jwa6o6r2/
Just do a simple check when increasing the month variable:
var month = monthAway.getMonth() + 3;
if(month > 12) //If it crosses 12, start from 1 again.
month -= 12;
Change
var month = monthAway.getMonth() + 3;
To
var month = ((monthAway.getMonth() + 3) % 12) + 1;
The ((monthAway.getMonth() + 3) % 12) will give you a number from 0 to 11. Since you want 1 - 12, that's where the + 1 comes in.
For the year issue, try the following
var year = (month <= 3 ? monthAway.getFullYear() + 1 : monthAway.getFullYear());
This will check if the month is less than or equal to 3, which would only be possible if you've wrapped around.
Thanks to all the other SO questions regarding javascript and comparing dates, I was able to come up with something that works well for my situation. Now, I just need to clear the input field if the date entered is more than 30 days old.
function ChngStatusEffective(obj)
{
p=/(\d{1,2})\/(\d{1,2})\/(\d{1,4})/;
if (!obj.value.match(p)) return;
num=new Array();
num=obj.value.match(p);
if (num[1].length == 1) num[1]="0" + num[1];
if (num[2].length == 1) num[2]="0" + num[2];
if (num[3].length == 1) num[3]="200" + num[3];
if (num[3].length == 2) num[3]="20" + num[3];
strValue= num[1] + "/" + num[2] + "/" + num[3];
var today = new Date ();
var Date2 = new Date (strValue);
var Days = Math.floor((Date2.getTime() - today.getTime())/(1000*60*60*24));
alert('Days between two dates is: ' + Days);
if (Days >= 0)
{
alert('Future dates are not allowed ' + Days);
// document.getElementByName('statuseffective').value();
$('#stauseffective').val('');
return false;
}
else if ((Days === -1) || (Days > -31))
{
alert('Date entered looks good' + Days );
}
else
{
alert('Are you sure you entered the correct date? ' + Days);
}
validateUSDate( strValue )
}
The function is called:
<input type="text" name="statuseffective" onchange="ChngStatusEffective(this)" />
I need only this input field name, statuseffective to be blanked. NOTE: there could be one input field or there could be 100. I only need the one input field blanked.
Since you are passing this to the ChngStatusEffective method you can use it to set its value.
$(obj).val('');
or
obj.value = '';
$('input[name="statuseffective"]').val('');
should do it, but if you have any other inputs with that name, it will clear them as well - using an id on that input and selecting it based on id would make sure no other inputs were cleared