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.
Related
This question already has answers here:
How to break out of jQuery each loop?
(7 answers)
Closed 3 years ago.
I have a fairly basic inquiry regarding how to stop an .each() loop after the conditions have been met. I have a notification counter that displays the number of Issues within a given timeframe. It works, but if I were select another option, it will add up the notifications, which is not good. Below is an example of Issues within 24 hours. I also have an option for Issues within one week and 30 days.
For example, if I were to select 24 hours, it will show: 2
If I were then to select One Week, it will 12 (One Week = 10)
I've tried 'return false' at the end of the loop, but no luck.
Let me know if you can help me out. Thank you.
// # of Issues within 24 hours
var newIssues, openIssues, closedIssues;
newIssues = 0;
openIssues = 0;
closedIssues = 0;
$('.newIssueCount').text('-');
$('.openIssueCount').text('-');
$('.closedIssueCount').text('-');
$('ul.timeFrameRange li:nth-child(1)').click( function(e) {
e.preventDefault();
$.each(parsedData, function (index, item) {
if (moment(item.CreatedDate).isAfter(twentyFourHours)) {
newIssues++;
$('.newIssueCount').html(newIssues);
if (item.IsClosed == false) {
openIssues++;
$('.openIssueCount').html(openIssues);
}
else if (item.IsClosed == true) {
closedIssues++;
$('.closedIssueCount').html(closedIssues);
}
else if (newIssues == 0 || openIssues == 0 || closedIssues == 0) {
$('.newIssueCount').html('0');
$('.openIssueCount').html('0');
$('.closedIssueCount').html('0');
}
}
return false;
});
});
Please try to return false from an anonymous function:
if (your_condition) return false;
How to format Date in Angular Java script?
Code
<p id="summaryHeader">Calendar of {{dt}}</p>
I get the value as
2014-06-05T12:38:42.744Z
I tried this
<p id="summaryHeader">Calendar of {{dt|date:'MMMM dd'}}</p>
which gives me
Calendar of June 05
I need it as Calendar of June 05th or July 2nd and so on.. the rear rd,th,st is what I am looking for.
Anuglar Docs are good but don't specify this formatting.
I guess this is what you are looking for - http://www.michaelbromley.co.uk/blog/13/an-ordinal-date-filter-for-angularjs
A custom filter using the logic
app.filter('dateSuffix', function($filter) {
var suffixes = ["th", "st", "nd", "rd"];
return function(input) {
var dtfilter = $filter('date')(input, 'MMMM dd');
var day = parseInt(dtfilter.slice(-2));
var relevantDigits = (day < 30) ? day % 20 : day % 30;
var suffix = (relevantDigits <= 3) ? suffixes[relevantDigits] : suffixes[0];
return dtfilter+suffix;
};
});
And a Demo: http://plnkr.co/edit/HiyQ9uvxQL3FRoj7hKB8?p=preview
I wanted to have the ordinal indicator as a superscript, so used the following:
<div>{{amount}}<sup ng-bind="amount | ordinal"></sup></div>
Using the filter:
app.filter('ordinal', function() {
return function(number){
if (isNaN(number) || number < 1){
return '';
} else if (number % 100 == 11 || number % 100 == 12) {
return 'th';
} else {
var lastDigit = number % 10;
if (lastDigit === 1) {
return 'st';
} else if (lastDigit === 2) {
return 'nd';
} else if (lastDigit === 3) {
return 'rd';
} else if (lastDigit > 3) {
return 'th';
}
}
}
});
Note that this correctly renders 11th, 12th, 111th, 1012th, and not 11st.
You are correct that the date filter does not provide this formatting... I would suggest that you either write your own filter, or just do this:
Calendar of {{dt|date:'MMMM dd'}}{{getOrdinal(dt)}}
if you write your own, I would start with the one from angular as a baseline.
EDIT the idea of writing your own in the answer provided by guru is the approach I would take.
To expand upon the example he created, I would tweak it so that you can use this syntax:
Calendar of {{dt|date2:'MMMM ddoo'}}
Where oo is the ordinal suffix
I updated this representative plnkr to give you maximum flexibility.
For anybody that hits this question there is the project https://github.com/chrisiconolly/angular-all-ordinal-filters (full disclaimer: my own project) that will give you a ordinal number filter for angular.
Its used as so:
{{number | ordinal}} // 1 -> 1st
{{number | ordinalOnly}} // 1 -> st
It's fully tested and running through travis so it will remain stable.
You could wrap your date in a momentjs object like
$scope.dt = moment($scope.dt);
then do
<p id="summaryHeader">Calendar of {{dt.format("ddd Do")}}</p>
Other options may be better unless you already use momentjs elsewhere, just an option.
While not my best work you can start with this as a baseline
http://plnkr.co/edit/v2RuF72A9OPpFj5fvN8A?p=preview
I am looking for a regex pattern to validate a string and see if this is an valid time. It can only be up to one hour. I want to check if a string is a valid time or return false.
It needs to be in mm:ss format
Good = 00:00
Good = 60:00
Bad = 60:01
Bad = 89:09
Bad = 3445
Using regex to validate number ranges is not an optimal solution. You need to create a quite long pattern to evaluate easy conditions. You'd be probably better of checking only if it's a number:number pattern then split it and check if the parts are consistent with your requirements or not:
function checkTime(time) {
if (time.match("^[0-9]{2}:[0-9]{2}$") === null) {
return false;
}
var parts = time.split(':');
if (parts[0] > 60) {
return false;
}
if (parts[0] == 60 && parts[1] > 0) {
return false;
}
return true;
}
That being said you can create a regex for this if you really want:
function checkTime(time) {
return time.match("^(60:00|[0-5][0-9]:[0-5][0-9])$") !== null;
}
It's just much harder to maintain and read this kind of code later on.
My shot at it:
function validate(input){
var split = input.split(':'), // split the input
part1 = +split[0], part2 = +split[1]; // try to parse parts to numbers
if(!part1 || !part2) return false; // didn't get 2 valid numbers
return (part1*60 + part2) < 3600; // check if they're less then 1 hour
}
console.log(validate('55:09')); // true
console.log(validate('61:09')); // false
console.log(validate('6155')); // false
http://jsfiddle.net/LGheT/
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.
First of all apologise for creating my third Javascript question in as many days - I'm really trying to push myself in this field on this project, and feel my skills are developing at a fairly good rate thanks to my research and your fantastic help on here, particularly redsuqare!!
I've got a table where people can enter times, and have a mask in place where it'll check that the input is in the format 99:99 - which is great, but ideally I want to limit it to be no more than 23:59!
Here's the code I have at the moment, cobbled together the best I can, but unsurprisingly doesn't work...
$.each($('#hoursavailable tr td :checkbox'), function() {
var $this = $(elem); // cache the object
var $row = $this.closest('tr'); // find the nearest table row
if($this.is(':checked')) {
// do nothing!
} else {
$row.each(':text'),function() {
var splittime = $(this).split(":");
if(splittime[0] > 22 || splittime[1] > 58) {
alert('please enter a valid date'); return false;
}
}
}
});
Could also be worth noting that there are two inputs per row/tr - it'd be absolutely ideal if I could somehow compare the two, to ensure that the first one is before the second, but appreciate that could be even more beyond me than the current stuff :(
Thanks
This may be what you are looking for-
http://www.the-art-of-web.com/javascript/validate-date/
I think all you need is the following change since your doing an each around the text inputs so you need to get the value out and split that.
$row.find(':text').each(function() {
var splittime = $(this).val().split(":");
if(splittime[0] > 22 || splittime[1] > 58) {
alert('please enter a valid date'); return false;
}
});
However to save yourself re-inventing the wheel why not look into the validate plugin where you can configure regex expressions to deal with data validation.
Although I do appreciate hand rolling is also a good learning curve.
You're going mad with your eaches when you really only need one
This ought to get you going with a few caveats as detailed below.
$("#hoursavailable :checked").each(function() {
var splittime = $(this).parents("tr").find(":text").val().split(":");
if (splittime[0] > 22 || splittime[1] > 58) {
alert('please enter a valid date');
return false;
}
});
I've assumed here that you only have one text box (hence .find(":text") on the parent. You could consider adding a class, but bear in mind that class selectors are slow.
There is no validation here, so you might want to add a little more, however the premise works.
Synthesis from different methods to check for max & format together.
var timeFieldValue = $(this).val();
re = /^\d{1,2}:\d{2}([ap]m)?$/;
if(timeFieldValue != '' && !timeFieldValue.match(re)) {
alert("Invalid time format: " + timeFieldValue);
$(this).focus();
return false;
}
var splittime = timeFieldValue.split(":");
if(splittime[0] > 23 || splittime[1] > 59) {
alert('Please enter a valid time');
return false;
}