comparing current date and date inp [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
i wanted to know whats the error in this code. i wanted to compare today's date with the user input date
<script type="text/javascript">
function validate()
{
if( document.myForm.name.value == "" )
{
alert( "Please provide your date of birth!" );
document.myForm.dob.focus() ;
return false;
}
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var Y = q.getFullYear();
var date = new Date(Y,m,d);
var r = document.getElementById(dates).value;
var m1 = r.getMonth();
var d1 = r.getDate();
var Y1 = r.getFullYear();
var mydate = new Date(Y1,m1,d1) ;
if(date<=mydate)
{
alert("greater");
return false;
}
else
{
alert("smaller");
return false;
}
return true;
}
</script>
<form name="myForm" method="post" onsubmit= "return(validate());">
Name: <input type="text" name="name"><br>
Date: <input type="date" id="dates" name="dates">
<br/>
<INPUT TYPE="submit" VALUE="Submit" >
</form>
i felt like "var r = document.getElementbyid(dates).value;" this piece of code is not working

The function name should be:
document.getElementById
(you are missing some capital letters)
Also, you are treating the result of document.getElementById(dates).value as though it will give you a Date object back, but it will actually give you are string - you need to convert this into a Date before you can call getMonth/getData/getFullYear on it - the answers to this question should help you here.

I have put comments below where the main errors in the code are.
function validate()
{
if( document.myForm.name.value == "" ) // Not an error per se, but you should use === to compare strings this way
{
alert( "Please provide your date of birth!" );
document.myForm.dob.focus() ;
return false;
}
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var y = q.getFullYear();
var date = new Date(Y,m,d); // The variable Y is not defined. You probably meant lowercase y.
var r = document.getElementbyid(dates).value; // Wrong case. Should be: document.getElementById
var m1 = r.getMonth();
var d1 = r.getDate();
var y1 = r.getFullYear();
var mydate = new Date(Y,m,d) ; // Same thing, probably meant lowercase y again.
if(date<=mydate)
{
alert("greater");
return false;
}
else
{
alert("smaller") // This statement is missing a semicolon
return false;
}
return true;
}
Also, it's not entirely clear what you are trying to do. At the end, assuming you fix those syntactical errors, you have three Date variables:
q, which is created with the current date and time.
date, which is just passed the same current date and time that was in q.
mydate, which... also holds the current date and time, since you just passed it the same values from q that you passed to date.
So since the two date objects you are comparing are set to the same date, you will always alert "greater" (which is not really greater, because they are equal, but that is a separate issue).
I also find it strange that this validation function returns false in all cases. Because of your if/else statement, there is no way to ever return true. For a function that is supposed to validate something, it seems odd to have the validation always return false.
Additionally, as #codebox stated in his answer, document.getElementById(dates).value is just returning a string, which you must then convert into a new Date object if you wish to read the date values from it into your m1, d1, and y1 variables (which, as of right now, are never even used).

You are having couple of typo and logic mistake. This code should work.
function validate()
{
if( document.myForm.name.value == "" )
{
alert( "Please provide your date of birth!" );
document.myForm.dob.focus() ;
return false;
}
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var y = q.getFullYear();
var date = new Date(y,m,d);
var r = Date.parse(document.getElementById("dates").value);
if(date<=r)
{
alert("greater");
return false;
}
else
{
alert("smaller");
return false;
}
return true;
}

Related

Javascript Simple If Else innerHTML == 'something' not working

I have a seemingly simple javascript function I am trying to create that checks the value of an elements innerHTML and spits out a value based on the answer, but for the life of me I can't get it to work and don't get any errors. This function is triggered by onclick events and doesn't need to have window.onload added. Any insight anyone could give me would be much appreciated! Here is my HTML
<div class="col-md-8 col-xs-9 product-info">
<p id="planTitle" class="bold m-b-2">20 DAY SUPPLY // 40 CAPSULES // FMF</p>
<p>Price: <span class="pull-right" id="plan-amount">$79</span></p>
<p>Tax: <span class="pull-right">Included</span></p>
<p id="shipping-line">Shipping: <span class="pull-right" id="cart-shipping-cost">$9.99</span></p>
<p class="hidden">Coupon: <span class="pull-right" id="coupon-code">firstmonthfree20day</span></p>
</div>
And my Javascript
function updateShippingCost(country_region) {
var url;
var kkdk = '';
var planTitleesd = document.getElementById('planTitle').innerHTML;
console.log(planTitleesd);
if (planTitleesd == '10 Day Supply // 20 Capsules // FMF') {
kkdk = '5.99';
console.log(kkdk);
} else if (planTitleesd == '20 Day Supply // 40 Capsules // FMF') {
kkdk = '9.99';
console.log(kkdk);
} else if (planTitleesd == '30 Day Supply // 60 Capsules // FMF') {
kkdk = '14.99';
console.log(kkdk);
}
}
Oddly, console.log(planTitleesd) returns a value, such as
"20 DAY SUPPLY // 40 CAPSULES // FMF"
but all the other console.log(kkdk) do not. Thanks for your help!
I have updated the original question with the relevant HTML, sorry about that.
You are doing a case-sensitive comparison. You've indicated that the resultant value is all caps, while you're comparing it to Title Case. Consider doing a case-insensetive comparison by calling toLowerCase on both operands before comparison. Also, please actually post your markup. Troubleshooting code questions must contain an MCVE. – CollinD 9 mins ago
This was the simple answer to the simple question I was looking for - Thanks CollinD!
Almost for sure you have newline at the beginning/end of planTitleesd.
Try to replace console.log(planTitleesd); by console.log('>' + planTitleesd + '<'); to check that.
Here is an example:
https://jsfiddle.net/324aw9zz/1/
You should avoid any spaces/newline between the tag opener/closer and the text itself:
<th id=planTitle>lala</th>
instead of
<th id=planTitle>
lala
</th>
Why not do something more along the lines of:
Using .indexOf() to check for one (or multiple) Strings?
function updateShippingCost(country_region) {
var url;
var kkdk = '';
var planTitleesd = document.getElementById('planTitle').innerHTML;
if ( planTitleesd.indexOf('10 Day') > -1 && planTitleesd.indexOf('20 Capsules') > -1 ) {
kkdk = '5.99';
} else if (planTitleesd.indexOf('20 Day')) {
kkdk = '9.99';
} else if (planTitleesd.indexOf('30 Day')) {
kkdk = '14.99';
}
}
I also agree that you should remove the case sensitive strings, as, (once again), typos and the like can occur.
Chances are there is just a typo in the value, or perhaps an empty return/newline you may be looking over.
Make sure all Carriage Returns and more are removed from the response. Seeing as, some items may actually add one that you do not notice. (Such as an openly tabbed div)
It sounds like this app is a store, something that could get pretty big. I would suggest is maybe an object that returns back the result you need.
The following a JSFiddle that I feel would simplify your process if you could create a proper JSON object.
https://jsfiddle.net/0sscf798/
function updateShippingCost(country_region) {
var url;
var kkdk = '';
var planTitleArr = [];
var planTitleObj = {};
var planTitleesd = document.getElementById('planTitle').innerHTML;
// This would most likely be a JSON response of items from the page/category
planTitleObj = {
"10 Day Supply": {
"20 Capsules": {
"FMF": 1.23
}
},
"20 Day Supply": {
"20 Capsules": {
"FMF": 4.56
}
}
};
planTitleArr = planTitleesd.split(" // ");
var price = planTitleObj[planTitleArr[0]][planTitleArr[1]][planTitleArr[2]] || "There is a problem with the price."
alert("The Price is: " + price);
}
updateShippingCost('');

Why is my custom validation in Angular2 not working

Here are two angular2 custom validations that I wrote, the first one validateAge works, but the second one validateDob does not ... the difference is the validateAge uses the component that I am on and is a text based field, the second one needs to use a Date Entry field and find the difference between today's date and the birthdate to find the actual age and then measure it against the age field. but something is not right ... any ideas
function validateAge(control: FormControl): { [s: string]: boolean } {
if (parseInt(control.value) <= 0) {
return {invalidAge: true};
}
}
function validateDob(control: FormControl): {[s:string]: boolean}{
var today = new Date();
var calcAge = today - control.value;
if (calcAge != parseInt([{age}]) ){
return {invalidDate: true}
}
}
The issue you have here is that your control.value is not a Date object, but rather the string representation.
var today = new Date();
Difference in milliseconds between the current timestamp and the entered value
var diff = today - new Date(control.value);
divide by ms per year and take the floor
var calcAge = Math.floor(diff/ (1000*60*60*24*365)));
Now do whatever comparison you need against the appropriate value. You didn't show us what your age object is so I don't actually know what comparison you're looking for.
if (calcAge < someAgeThreshold) ){
return {invalidDate: true}
} else {
return null;
}
Also note that with custom validation the validator returns no error when you return null and anything with a value is considered to have an error.

getFullYear doesn't return anything

Im in the land of JavaScript and I'm trying some functions for my university project, but I got stuck in this part:
function validateDate(){
alert("validateDate");
var date = document.getElementById("dateN");
var yearN = data.getFullYear();
alert(yearN.value);
var dateA = new Date();
var yearA = dateA.getFullYear`enter code here`();
alert(yearA.value);
if(((yearA - yearN)<18) || ((yearA - yearN)>120)){
alert("age between 18 and 120 only.");
data.style.backgroundColor = "red";
}
}
When I try to print the values, nothing happens, Which terrible wrong thing Im doing here guys?
The dateN is comes from another part (which is working =D ).
Sorry if its a very "noob" question,
Thanks in advance!
There is two mistake here :
var date = document.getElementById("dateN");
var yearN = data.getFullYear();
date is refering a DOM element an it is not a date !
data is undefined !
maybe you want make a Date with the value from "dateN" ?
so according to the HTMLElement you have to get his value and create a new Date !
// saying is a input text and a valid date format !
var date = new Date( document.getElementById("dateN").value );
var yearA = dateA.getFullYear`enter code here`();
// ^
// this is not valid o----------------|
You are calling data.getFullYear() -
var yearN = data.getFullYear();
Don't you mean date.getFullYear??

Compare multiple date fields on a page through javascript

How to efficiently compare dynamic number of dates on a page from a given date?
Consider following code:
<div id="dateFields">
<input type="date" id="date1"/>
<input type="date" id="date2"/>
<input type="date" id="date3"/>
<input type="date" id="date4"/>
<input type="date" id="date5"/>
</div>
<div id="masterDate">
<input type="date" id="comparator"/>
</div>
<button onClick="compareDate()">Compare Now</button>
Consider the dates in div with id="dateFields are in random numbers. Say 5 for now. And the date in div with id="comparator is the date which we need to compare all the dates with.
Now, for example, if the comparator date is set to "March, 2015" and all the values in dateFields are set dynamically by the user (Say "Feb, 2002", "Dec, 2010", "Aug, 2016", "Jul, 2019" and "Nov, 2015"). What is the most efficient and generic code I should write in the function compareDate() so that the output brings all the dates which are greater than the comparator.
Edit:
Here is my javascript function. But, I don't feel that this is the efficient way. And even this is no good for dynamic number of values.
function compareDate() {
var v1 = document.getElementById("date1").value;
var v2 = document.getElementById("date2").value;
var v3 = document.getElementById("date3").value;
var v4 = document.getElementById("date4").value;
var v5 = document.getElementById("date5").value;
var v6 = document.getElementById("comparator").value;
var v7 = [ v1, v2, v3, v4, v5 ];
var result = "";
for (i = 0; i < v7.length; i++) {
console.log(solidify(v7[i]));
if (solidify(v6) < solidify(v7[i])) {
result += v7[i];
}
}
document.getElementById("result").innerHTML = result;
}
function solidify(date) {
var tempResult = '';
for (i = 0; i < date.length; i++) {
if (date.charAt(i) == '-') {
continue;
}
else {
tempResult += date.charAt(i);
}
}
return tempResult;
}
Edit 2:
Explanation of the requirement with example.
There need not be any text-box, it may be just a set of <td>, <p> or may be just a <div> containing number of dates, which may vary from minimum 2 dates to max 50 dates(Say).
I'm just looking for a logic and hence was trying with text-boxes.
For a real time example, consider a City Municipality Management System, which keeps track of monthly deaths that occur in that city. Now, a clerk wants to know the details of citizens who died after 15th of that month, how will he get the data?
The following code does what you are asking, but there are still some requirements that you need to nail down, in order to make it truly "generic" (see below the code):
HTML
<div id="dateFields">
<input type="date" id="date1"/>
<input type="date" id="date2"/>
<input type="date" id="date3"/>
<input type="date" id="date4"/>
<input type="date" id="date5"/>
</div>
<div id="masterDate">
<input type="date" id="comparator"/>
</div>
<div id="results">
Results: <span id="resultDates"></span>
</div>
<button onClick="compareDate()">Compare Now</button>
JavaScript
<script>
function compareDate() {
var aDates = document.getElementById("dateFields").getElementsByTagName("input");
var sCompareDate = document.getElementById("comparator").value;
var dCompareDate = formatDate(sCompareDate);
var result = "";
for (i = 0; i < aDates.length; i++) {
var sCurrDate = aDates[i].value;
if (dCompareDate < formatDate(sCurrDate)) {
if (result.length > 0) {
result += ", ";
}
result += sCurrDate;
}
}
if (result === "") {
result = "No dates less than " + sCompareDate;
}
document.getElementById("resultDates").innerHTML = result;
}
function formatDate(sDate) {
var regMonthYear = /[a-z]{3}, \d{4}/i;
if (regMonthYear.test(sDate)) {
sDate = sDate.replace(",", " 1,");
}
return new Date(sDate);
}
</script>
Things that need to be worked out still:
You must compare Date objects, not strings.
To do what you are trying to do, you must use JavaScript Date objects. Even if you are using am <input> with a type attribute of "date", its value is still a string. If you compare that, it would be like asking if "orange" is less than "house" . . . JavaScript will give you an answer, but it will be, in no way, related to what you are looking for.
The JavaScript Date object has built in comparison functionality that will do exactly what you are looking for.
2 You need to come up with some sort of standard for your date inputs and make sure that you have code to enforce them.
While the Date object is VERY flexible when it comes to what inputs it will accept when you are creating a new instance, it does have its limits. You can look at these two links for more information on valid string formats for creating dates:
the ISO date format - https://msdn.microsoft.com/en-us/library/ie/ff743760%28v=vs.94%29.aspx#ISO
other date parsing rules - https://msdn.microsoft.com/en-us/library/ie/ff743760%28v=vs.94%29.aspx#OtherDateFormats
Once you figured out which one(s) make the most sense for your needs, you really should set a common format (or group of formats) that you want to work with, and enforce that formatting on your inputs with validation rules. If you don't, you will have to add LOTS of logic to validate all of the different possibilities, so that you know that you are going to get a valid Date object when you try to create it.
3 You need to come up with some sort of standard output for your results.
Ideally, if you want to create a truly "generic" date comparison function to meet what you are asking for, you want it to focus solely on the comparison and nothing else. Something like this:
function compareDate(aDateGroup, dComparisonDate)
var aGreaterThanDates = [];
for (i = 0; i < aDateGroup.length; i++) {
if (dCompareDate < aDateGroup[i]) {
aGreaterThanDates.push(aDateGroup[i]);
}
}
return aGreaterThanDates;
}
. . . where aDateGroup is an array of Date objects and dCompareDate is a Date object as well.
The function would take in the dates, compare them, and pass back the ones that passed the test. Then you could cycle through the returned array and process those dates however you needed to.
This would also allow you to pass in dates from any source (i.e., like a collection of the <td>, <p>, and <div> elements that you mentioned in your second update), as long as they were converted to proper Date objects first.
Determine whether or not you need to be flexible in your comparison.
The above "ideal code" could actually be made even "more ideal" by adding some flexibility in the comparison function, by adding a few parameters to indicate what kind of comparison to do:
function compareDate(aDateGroup, dComparisonDate, sCompareDirection, bIncludeComparisonDate)
var aPassedDates = [];
for (i = 0; i < aDateGroup.length; i++) {
if (sCompareDirection === "before") {
if (bIncludeComparisonDate) {
if (dCompareDate >= aDateGroup[i]) {
aPassedDates.push(aDateGroup[i]);
}
}
else {
if (dCompareDate > aDateGroup[i]) {
aPassedDates.push(aDateGroup[i]);
}
}
}
else if (sCompareDirection === "after") {
if (bIncludeComparisonDate) {
if (dCompareDate <= aDateGroup[i]) {
aPassedDates.push(aDateGroup[i]);
}
}
else {
if (dCompareDate < aDateGroup[i]) {
aPassedDates.push(aDateGroup[i]);
}
}
}
else {
if (dCompareDate == aDateGroup[i]) {
aPassedDates.push(aDateGroup[i]);
}
}
}
return aPassedDates;
}
The sCompareDirection parameter would allow you to determine the direction of the comparison. "before" would check for values less than the comparison date, "after" would check for values greater than the comparison date, and any other value (or no value) would check for the dates being equal.
The bIncludeComparisonDate parameter would allow you to include the comparison date as part of the match. A value of true would turn the "greater than" comparison to "greater than or equal to" and the "less than" comparison to "less than or equal to".
Conclusion
Date comparison is actually a fairly common process, but it is also one that requires a LOT of thinking through to make flexible and foolproof. If you don't catch some of these things early, you are asking for a world of hurt down the line, when you try to reuse what you have built and in a situation that doesn't quite match what you originally set up. :)
you can do it in following way :
<script>
function compareDate() {
var v1 = document.getElementById("date1").value;
var v2 = document.getElementById("date2").value;
var v3 = document.getElementById("date3").value;
var v4 = document.getElementById("date4").value;
var v5 = document.getElementById("date5").value;
var v6 = document.getElementById("comparator").value;
var v7 = [ v1, v2, v3, v4, v5 ];
var finalResult = "";
for (k = 0; k < v7.length; k++) {
if (solidify(v6) < solidify(v7[k])) {
finalResult += v7[k];
finalResult += " and ";
}
}
document.getElementById("result").innerHTML = finalResult;
}
function solidify(date) {
var result = '';
for (i = 0; i < date.length; i++) {
if (date.charAt(i) == '-') {
continue;
} else {
result += date.charAt(i);
}
}
return result;
}
</script>
function compareDate() {
var dateFields = document.getElementById('dateFields').getElementsByTagName('input');
var comparatorDate = new Date(document.getElementById('comparator').value);
var rslt = [];
for (var i = 0; i < dateFields.length; i++) {
if (new Date(dateFields[i].value) > comparatorDate) rslt.push(dateFields[i].value);
}
return rslt;
}
This was tested in chrome

Regex not matching properly

Ive been working on this regex for days now and I cant get it figured out. It either passes everything I put in there or it kicks everything out and I cannot seem to make it function. Admittedly I am new to doing this complex of stuff with Javascript so It may be that you realy cant do this.
I want to check onkeypress what was entered into the input and then validate it to x, y, or z. Then from there send it on about its way to do other neat stuff.
So the question is what the heck am I not understanding about RegExp?
Here is a FIDDLE for it.
function val() {
var gradeIn = document.querySelectorAll("#letGrade input[type=text]");
var checkGrade = new RegExp(/[xyz]/gi);
for (var i = 0; i < gradeIn.length; i++) {
if (!checkGrade.test(gradeIn.value)) {
alert ("This must be X, Y, or Z");
return false;
} else {
return true;
}
}
};
EDIT/UPDATE:
I was trying to do this on keypress and validate each text input individualy however this was realy kinda squishy in the grand scheme of things and not working out exactly correct. I decided to validate all text inputs onsubmit and have everything go all at once. Updated code is below.
function calcGPA() {
var grades = document.querySelectorAll("#letGrade input[type=text]");
var contacts = document.querySelectorAll("#conHours input[type=text]");
var gVals = [];
var cVals = [];
var failGrade = "The Letter Grade input may only be A, B, C, D or F";
var failHours = "The Contact Hours input may only be 1, 2, 3, 4 or 5";
var checkGrade = /^[ABCDF]/;
var checkhours = /^[12345]/;
for (var i = 0; i < grades.length; i++) {
if (!checkGrade.test(grades[i].value)) {
alert(failGrade);
return false;
}
if (!checkhours.test(contacts[i].value)) {
alert(failHours);
return false;
}
gVals.push(grades[i].value);
cVals.push(contacts[i].value);
}
//Other cool stuff happens here
};
Now to just finish the conversion piece for the letters to numbers and the math piece. Thank you for your help on this!
The problem's not only with your regular expression.
if (!checkGrade.test(gradeIn[i].value)) {
You weren't checking each grade. Now if you want it to only be those characters, you have to extend the regular expression a bit. Also, there's no point calling new RegExp if you're using native syntax.
var checkGrade = /^[xyz]+$/;
That means that you're OK with the fields being like "xxyyz" or "zzy". If it should just be one character, that'd be
var checkGrade = /^[xyz]$/;

Categories