I am creating a survey and I need the submit button to be hidden on a specific date. In other words, I need the button to be hidden on 10/22/2013 only and for the button to be visible all other days. I have been ripping my hair out figuring out why the code below does not work...am I missing something?...
var x=new Date();
x.setFullYear(2013,9,22);
var today = new Date();
if (x=today)
{
document.getElementById('NextButton').style.visibility='hidden';
}
else if
{
document.getElementById('NextButton').style.visibility='visible';
}
You are assigning instead of validating:
var nextBtn = document.getElementById('NextButton'),
x = new Date(),
today = new Date();
x.setFullYear(2013,9,22);
if (x === today) {
nextBtn.style.visibility = 'hidden';
} else if {
nextBtn.style.visibility = 'visible';
}
Single = assigns, whereas == or === compares equality.
Side note:
=== is preferred (and therefore used above) because it verifies value and type. == verifies only value, i.e. 1 == '1' because the values match despite one being an integer and one being a string, however 1 !== '1' because while the value matches, the type does not. Just a little extra info.
Related
I'm working on a calculator with vanilla JavaScript. I'm trying to make an if statement to find out whether the current result displayed has only one number left in the string. If this is true I want to make sure when the user clicks the delete button the current display returns to the default display instead of having no numbers in the string. I hope I explained this properly. How would I go about making this check.
const deleteNumber = () => {
let newDisplayedResult = currentResult[0].innerHTML.slice(0, -1);
if (firstNumber !== "" && currentOperator !== "") {
secondNumber = newDisplayedResult;
currentResult[0].innerHTML = newDisplayedResult;
} else {
firstNumber = newDisplayedResult;
currentResult[0].innerHTML = newDisplayedResult;
}
};
let re = new RegExp('^[0-9]$');
re.test(str)
or:
str.length === 1 && "0123456789".split("").includes(str)
var dayInput = document.querySelector("#day");
var monthInput = document.querySelector("#month");
var yearInput = document.querySelector("#year");
var day = document.querySelector("h2");
var h3 = document.querySelector("h3");
function runCode() {
dayPicked = Number(dayInput.value);
monthPicked = Number(monthInput.value);
yearPicked = Number(yearInput.value);
if (dayPicked <= 31) {
if (monthPicked <= 12) {
if ((monthPicked = 2) && (dayPicked <= 29)) {
day.textContent = (DispDay(dayPicked, monthPicked, yearPicked));
h3.textContent = (DispFullDate(dayPicked, monthPicked,
yearPicked));
} else { day.textContent = "Not Possible Dude!"}
} else { day.textContent = "Not Possible Dude!"}
} else { day.textContent = "Not Possible Dude!"}
}
This is a snippet out of my code where I am trying to limit the search for dates within my input boxes. For example, if February is chosen and the day is the 30th, it should throw out an error. But all that happens with the code you see above is no matter what month I choose, it keeps returning February. I know I am definitely doing something wrong, but I do not know what it is. BTW - I started learning JavaScript 3 weeks ago so I know my code is a mess. Thanks.
var button = document.querySelector("#goButton");
[dayInput, monthInput, yearInput].forEach(function (element) {element.addEventListener("keyup", function (event) {
event.preventDefault();
if (event.keyCode === 13) {
runCode();
}
});
});
I don't know if the EventListener needs to be added here but here it is anyway.
You're setting monthPicked
monthPicked = 2
You meant to use two == to check for equality.
However, the next problem you'll see is that your code will only work if the user selects February.
You probably wanted
if ((monthPicked != 2) || (dayPicked <= 29)) {
That way if they select february, it has to be before 29th. Any other month can be anything. Still incomplete logic as some months should allow 31 others not. But i'll leave that to you. (Also, leap years!)
= is an Assignment Operator. == is an Equal To Operator,compares value of left and side expressions. Change monthPicked = 2 to monthPicked == 2.
Here is my jsFiddle
Its on the Phone method, no the name one
Now is this line right? I only want it to be true if the first 3 letters are 087
var RightStarting3 = value.substring(0,2) == (087);
if (BlankPass || LessThan10 || RightStarting3 || GreaterThan10 || (HasSpaces > 0))
{
document.getElementById('Phone').style.background = "red";
return false;
}
else {
document.getElementById('Phone').style.background = "white";
document.getElementById("PhoneTick").style.visibility="visible";
return true;
}
var RightStarting3 = value.substring(0,3) === ('087');
value.substring(x) returns a string and 087 and 87 mean the same to javascript interpreter. You should change one of the datatypes so that they match...
Either the substring to an integer:
var RightStarting3 = parseInt(value.substring(0,2)) == 87;
Or the value you're comparing against to a string:
var RightStarting3 = value.substring(0,3) == "087";
Secondly -- you are invoking ValidateName() immediately (in your assignment to NamePass). Is this really necessary? There will be empty values on page load.
I think with the javascript substring(x,y) method, the y value is the value at which to stop the selection. So in your example the first 3 characters will not be selected and instead the first 2 characters will be selected.
var a = "123";
// this returns "12"
alert(a.substring(0,2));
You probably want to use var RightStarting3 = value.substring(0,3) == ('087'); instead.
KingKongFrom's answer is correct, I would add that you should make sure that value (whatever that is) isn't null first, cause if you try to call substring on null it will thrown an exception and die.
I am quite new to Grails and in an application I need to check dates. In a former Java program I have used two javascript functions with different detail granularity. Both accept dates from 1970-01-01 to 2099-12-31. One demands a correct date and (optionally) time and just tells the user he/she made an erroneous entry:
function okdate1(dtstr) {
var ok = true;
// First trim off leading and trailing white space
var trimPattern = /(?:\b(.*)\b)/;
dtstr = (dtstr.match(trimPattern))[1];
// Verify that input is within range and correct
var pat = /^((?:19[7-9][0-9])|(?:20[0-9][0-9]))-((?:(?:0)?[1-9])|(?:1[0-2]))-((?:(?:0)?[1-9])|(?:[1-2][0-9])|(?:3[01]))(?: ((?:(?:0|1)[0-9])|(?:2[0-3])):([0-5][0-9]))?$/;
var dtm = dtstr.match(pat);
if (!dtm) {
ok = false;
} else { // Verify that day in in range for the given month
var days = Array(31,28,31,30,31,30,31,31,30,31,30,31);
// Compensate for leap year
if ((((dtm[1] % 4) === 0) && !((dtm[1] % 100) === 0)) || ((dtm[1] % 400) === 0)) {
days[1] = 29;
}
if (dtm[3] > days[dtm[2] - 1]) ok = false;
}
if (!ok) alert("Enter date and (optionally) time on the form 'yyyy-MM-dd HH:mm'");
return ok;
}
and the other that checks exactly what went wrong by accepting a wider range on the numeric parts of the input string:
function okdate2(dtstr) {
// First trim off leading and trailing white space
var trimPattern = /(?:\b(.*)\b)/;
dtstr = (dtstr.match(trimPattern))[1];
// If nothing then skip the rest
if (!dtstr) return datetimealert(0);
// Pattern to recognize any 'dddd-dd-dd[ dd:dd]' pattern
var pat = /^(?:(\d{4})-(\d{1,2})-(\d{1,2}))(?: (\d{1,2}):(\d{2}))?$/;
var dtm = dtstr.match(pat);
// If this is does not follow the pattern: get out
if (!dtm) return datetimealert(0);
// convert each group to a number
// if no time notation the corresponding groups become NaN
for (var i = 1; i < dtm.length; i++) {
dtm[i] = Number(dtm[i]);
}
// Check for correct year interval
if (dtm[1] < 1970 || dtm[1] > 2099) return datetimealert(1);
// Check for correct month notation
if (dtm[2] < 1 || dtm[2] > 12) return datetimealert(2);
// Array with correct numer of days for each month
var mdays = Array(31,28,31,30,31,30,31,31,30,31,30,31);
// Compensate for leap year
if ((((dtm[1] % 4) === 0) && !((dtm[1] % 100) === 0)) || ((dtm[1] % 400) === 0)) {
mdays[1] = 29;
}
// Check the day for the given month
if (dtm[3] < 1 || mdays[dtm[2] - 1] < dtm[3]) return datetimealert(3);
// If only date was given and no time, we are OK
if (isNaN(dtm[4]) && isNaN(dtm[5])) return true;
// This can not happen according to pattern, but ...
if (isNaN(dtm[4]) || isNaN(dtm[5])) return datetimealert(4);
// check given hour
if (dtm[4] > 23) return datetimealert(5);
// Check given minutes
if (dtm[5] > 59) return datetimealert(6);
// If no error
return true;
}
where the function datetimealert puts out an alert with a (hopefully) good error message and returns false. The 'trimpattern' in both function strip leading and trailing whitespace.
I used them in my forms where I made calls to them in an "onsubmit" function. My objective here is not to discuss the two functions but comments on them are, of course, welcome.
In my Grails application I use jQuery datepicker extended with Trent Richardsons jQuery timepicker addon, so I get a text string as a result. I call the datetimepicker in a form:
<form ...
<dl ...
<dt>Start date <span class="required-indicator">*</span></dt>
<dd>
<div class="fieldcontain ${hasErrors(bean: todoInstance, field: 'startdate', 'error')} required">
<g:textField name="startdate" id="datepicker" class="datepicker"
value="${formatDate(format:'yyyy-MM-dd HH:mm',date:todoInstance?.startad)}" required="" />
</div>
</dd>
...
For all the other 'required' fields I get a little 'tooltip'-like message telling me to
enter a value into the field.
Now, I want to use my two datetime javascript in my grails application but I don't want alert boxes popping up, I want to use them in the static-constraints section in the domain classes and get my messages in the same manner as for the other fields. How do I integrate them into the error management system i grails?
This error messages are provided by the validation API. To inplement your own customized validations you can use the constraint validator.
But I'm assuming that you already declared your field as java.util.Date in the domain class, so you need a Date object in the validator. By default, Grails handle dates with g:datePicker, that will split the date in day, month and year fields.
To bind a single String with some format to a date object, you can register a custom Date Property Editor, like this example.
The Grails validation API is for server side validation. In your case one option is the JQuery Validation UI Plugin, that provides client side validation through JQuery. The plugin supports all standard constraints and you can create your own validations (like your date validations), checkout the extensibility docs session.
Using Jquery TableSorter, I am creating a custom parser to sort elapsed time <td>s that contain "'#' year(s) * '#' month(s)". When I use the function
$('.techtable td:nth-child(6)').each(function(){
// console.log($(this));
var that = $(this).text();
var myRegexp = /([\d]+) ([\w]+)(?: ([\d]+) ([\w]+))?/;
var match = myRegexp.exec($(this).text());
console.log(match);
});
from the command line, each index contains an array of length 5, looking like this:
["7 months", "7", "months", undefined, undefined]
to this:
["3 years 3 months", "3", "years", "3", "months"]
depending on whether or not the elapsed time has just a month or year element, and then the other. To parse the text, I use regex to gather each element, and then use JS to test whether there are multiple elements or not, and if 1 element only, then wheher it begins with "y" or "m", and return the number of months, so the parser can sort the <td>s by number of months in integer form.
The parser passes in each element into the function as parameter "s". when i try regex on "s" directly, it is not returning an array of length 5, it is truncating it to 3 (whether or not I am running the line that truncates it if index 3 is typeof 'undefined'). When I use the console to directly use this function:
$('.techtable td:nth-child(6)').each(function(){
// console.log($(this));
var that = $(this).text();
var myRegexp = /([\d]+) ([\w]+)(?: ([\d]+) ([\w]+))?/;
var match = myRegexp.exec($(this).text());
if (typeof match[3] == 'undefined') {match.length = 3;};
console.log(match);
});
the regex returns the arrays properly, with the array truncated if it only has 1 element (year or month). Here is the code for the custom parser:
var myRegexp = /([\d]+) ([\w]+)(?: ([\d]+) ([\w]+))?/;
var match = myRegexp.exec(s);
var order = [];
console.log(match);
if (typeof match[3] == 'undefined') {match.length = 3;};
// 1 element case:
// month
if (match.length = 3) {
if (match[2][0] == "m") {
order.push(match[1]);
}
// year
if (match[2][0] == "y") {
order.push(match[1]*12);
}
// both elements
} else {
order.push(match[1]*12 + match[3]);
}
s = order;
return s;
},
The fiddle is here. The Elapsed parser is second from the bottom of the JS panel. As you can see, since I can't get the months from the array (indices 4 and 5), I can not calculate the months, and thus the sorting only incorporates years, and the months are sorted by their original HTML placement. What am I missing? (I'm learning.... so direction is appreciated more than an fix, but I won't turn it down.)
Yes I realize the JS fiddle is loaded (first part is TableSorter, to maintain functionality for verification(click on headers to sort), but all you need to focus on is the last part of the code (reference the '//Table Sorter dateSorter' to see how a correct parser should look). The section '//Table Sorter elapsedSorter' is where my two attempts are, the first part is the working code I use in the console, and the seconde part is the parser, which is somehow deleting the last two indices in the array, thus loosing the month information to calculate.
Guess I'll have to add Regex, and a personal rating of 1, since I've wasted almost an entire day on this.
if (match.length = 3) {
You meant this?
if (match.length == 3) {
To help you further, when you write conditions with one constant and a variable, you can write them like this instead:
if (3 = match.length) {
This would now cause a JavaScript error instead of silently getting turned into an assignment that always yields true.
In JavaScript, 12 + '4' == '124', so you have to be careful with numbers and the + operator. In languages such as PHP you don't have this problem, because they have an operator for string concatenations ;-)
var myRegexp = /([\d]+) ([\w]+)(?: ([\d]+) ([\w]+))?/;
var match = myRegexp.exec(s);
var order = [];
if (typeof match[3] == 'undefined') {
if (match[2][0] == "m") {
order.push(parseInt(match[1]));
}
// year
if (match[2][0] == "y") {
order.push(parseInt(match[1])*12);
}
// both elements
} else {
order.push(parseInt(match[1])*12 + parseInt(match[3]));
}
s = order;
return s;
Btw use parseInt(x, 10) if you expect fields to have leading zeroes (which would otherwise result in 0 being returned). Thanks fudgey!