How to break an $.each() loop when conditions have been met [duplicate] - javascript

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;

Related

How to make alert() come after .innerHTML? [duplicate]

This question already has answers here:
Javascript alert() supersedes preceding code
(4 answers)
Closed 2 years ago.
I currently have some code like this:
function markAlert() {
if (qnsAnsd == 4) {
alert("You got " + mark + "/4! Refresh page if you want to try again.")
};
}
function addEval() {
var addMrknElem = document.getElementById('q__add-mrkn');
qnsAnsdCntr();
document.getElementById('q__add-btn').disabled = true;
if (document.getElementById('q__add-ans').value == addSoln) {
addMrknElem.innerHTML = "Your answer is correct!";
markCntr();
} else {
addMrknElem.innerHTML = "Your answer is incorrect. The correct answer is " + addSoln + ".";
}
markAlert();
};
Basically title... I want the alert in markAlert() to pop up after the the .innerHTML takes effect.
just wrap your alert() method in the setTimeout See the example below.
setTimeout(() => {
markAlert()
}, 1000);
Here, 1000 means 1 second so this markAlert() will be invoked after 1 second. you can change this value to 500 means half a second too.

Sometimes nothing evaluates true in the If statements

I have these If statements based off of a Math.random() function and it works for the most part but sometimes nothing evaluates to true
I've tried changing the numbers that the Boolean statements compare too and I've tried changing the number that Math.random is multiplied by
var dodge = {
dodgeValue: function() {
return Math.floor(Math.random() * 10) + 1
},
roll: function() {
console.log('ROLL AFTER DODGE?'); //DELETE THIS
if (this.dodgeValue() <= 5) {
console.log('Ball Rolls to Person One');
dodgeBall.ball.position = 'on ground';
dodgeBall.personOne.ball();
}
if (this.dodgeValue() >= 5) {
console.log('Ball Rolls to Person Two');
dodgeBall.ball.position = 'on ground';
dodgeBall.personTwo.ball();
}
},
This is one of the two parts that have the same problem the other one when copied and pasted was really jumbled so I left it out but if anyone had any ideas on why this is happening or how to fix it that would be great.
You're generating two random numbers. A new one each time you write this.dodgeValue().
Additionally, if the value is exactly 5 then both branches will run - this probably isn't intended behaviour.
You should do something like let dodge = this.dodgeValue(); and then use if( dodge <= 5). Additionally, you should use else rather than an "if A then ... if not A then ..."
That's because you call dodgeValue twice, which calls random twice.
Ignoring the fact that random numbers in computers are actually psudeorandom for a second, let's look at what happens when you call dodgeValue twice to get two random numbers like you have.
You could conceivably get the following numbers from this code:
4
6 8
6 2
In the first case, the first if will be true and execute, since 4 <= 5.
The first if will be false, but the second if will be true, since 6 > 5 (first if is false) and 8 >= 5 (second if is true).
Now, what happens in that third case? Both if's will be false, since 6 > 5 (first if is false) and 2 < 5 (second if is false).
If that is how you intend for it to work (which I'm assuming not), keep your code as is. If not, you have 2 options depending on your needs.
If you need to store the output of dodgeValue for later, you can use a variable:
var dodge = {
dodgeValue: function() {
return Math.floor(Math.random() * 10) + 1
},
roll: function() {
console.log('ROLL AFTER DODGE?'); //DELETE THIS
var val = this.dodgeValue();
if (val <= 5) {
console.log('Ball Rolls to Person One');
dodgeBall.ball.position = 'on ground';
dodgeBall.personOne.ball();
}
if (val >= 5) {
console.log('Ball Rolls to Person Two');
dodgeBall.ball.position = 'on ground';
dodgeBall.personTwo.ball();
}
},
If you just need them to be opposites of each other, then just use an else clause instead.
var dodge = {
dodgeValue: function() {
return Math.floor(Math.random() * 10) + 1
},
roll: function() {
console.log('ROLL AFTER DODGE?'); //DELETE THIS
if (this.dodgeValue() <= 5) {
console.log('Ball Rolls to Person One');
dodgeBall.ball.position = 'on ground';
dodgeBall.personOne.ball();
} else {
console.log('Ball Rolls to Person Two');
dodgeBall.ball.position = 'on ground';
dodgeBall.personTwo.ball();
}
},

Nested IF statement doesn't work like I want it to

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.

Using jquery to show div if all above value's in form are true to criteria

For the most part I have this code working. I originally had it so that if the email field length was greater than 10 then on keyup a div below would show. That worked okay. However, I want to add more validation. Below is my jQuery and I'm not sure I'm using the correct syntax.
$('#primaryemail').keyup(function(){
if($(this).val().length > 11 && ('#first_name').val().length > 6 && ('#phone_number').val().length == 10)
$('#projectinfo').show();
else
$('#projectinfo').hide();
});
I'm sure where I went wrong is with the && operators getting that from JavaScript and not entirely positive this is the correct way with jQuery.
Originally I had just the primaryemail as the validation but then added the first_name & phone_number as well. Once I added that it didn't work.
It might help to check your syntax and break it to multiple lines:
$('#primaryemail').keyup(function(){
if(
$(this).val().length > 11 // I suggest you also use .trim()
&& $('#first_name').val().length > 6
&& $('#phone_number').val().length == 10
) { // Always helpful to use Brackets
$('#projectinfo').show();
} else { // Especially around 'else'
$('#projectinfo').hide();
}
});
My suggested alternative is this:
// Cache your variables, noting the comma at the end of the first
// three lines, and the semicolon at the end of the 4th one.
// If you add more, use a comma after each one except the last one.
var $firstName = $('#first_name'),
$primaryEmail = $('#primary_email'),
$phoneNumber = $('#phone_number'),
$projectInfo = $('#projectinfo');
// Now bind your event listeners
// and use a simple function name to keep it easy!
$primaryEmail.keyup(function(){
if(isValidData()) {
$projectInfo.show();
} else {
$projectInfo.hide();
}
});
// Create a function for your logic that return a simple Boolean
// This keeps your state checking separate from your actions
// which rely on that state. You may check states in multiple places
// so it might be helpful to put them in separate functions to avoid
// repetition in the future.
function isValidData(){
return (
11 < $primaryEmail.val().trim().length
&& 6 < $firstName.val().trim().length
&& 10 == $phoneNumber.val().trim().length
);
}

single digit counting using numbers and letters in javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Convert a number to the shortest possible character string while retaining uniqueness
I want to count something and I only have a single digit to report the result, so I want to use letters for numbers > 9. E.g.
1 => 1
5 => 5
10 => A
30 => U
55 => u // I may have an off-by-one error here -- you get the idea
>61 => z // 60 will be more than enough, so I'll use z to mean "at least 62"
What's the easiest way to do that using javascript?
Here's one of the many ways to do it:
function num2letter(num) {
if( num > 61) return "z";
if( num < 0) return num;
return "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[num];
}
I decided base 36 was good enough:
function oneDigit(n) {
var BASE=36;
if (n >= BASE-1) { n = BASE-1; }
return n.toString(BASE);
}
Another way to do it:
function parse(x)
{
if(x<10)return x;
else if(x<36)return String.fromCharCode(x+55).toUpperCase();
else if(x<62)return String.fromCharCode(x+29).toLowerCase();
else return "z";
}
And this little test:
var res="";
for(var a=-10;a<70;a++)res+=a+" -> "+parse(a)+"\n";
alert(res);
And a fiddle: http://jsfiddle.net/nD59z/4/
And the same way, but with less characters and incomprehensible:
function parse(x)
{
return x<10?x:(x<36?String.fromCharCode(x+55).toUpperCase():(x<62?String.fromCharCode(x+29).toLowerCase():"z"));
}

Categories