How to convert number to bool in JS? - javascript

I trying to convert number to boolean,
but my if condition always run the else block statements.
if ( !($(document).find($('.formSectionWrapper').length)) ) {
console.log('IF')
} else {
console.log('ElSE')
}
when length is 0 it runs else and when it is greater than 0 it run else block again!
What is my mistake?

Just change
if(!($(document).find($('.formSectionWrapper').length)))
to
if(!($(document).find($('.formSectionWrapper')).length))
Note the parenthesis.

In Javascript 0 is falsy and positive numbers are truithy
so you can just check on the number.
To answer your question:
Your logic looks wrong because of your ! you are inverting the logic which is likely confusing you.

According to jQuery Doc find, you find an element not the length.
Description: Get the descendants of each element in the current set of
matched elements, filtered by a selector, jQuery object, or element.
Then you apply the if...else statement on the length.
So here is how your code shall look like
const formSectionWrapper = $('.formSectionWrapper');
//const formSectionWrapper = $(document).find('.formSectionWrapper');
if ( !formSectionWrapper.length ) {
console.log('IF')
} else {
console.log('ElSE')
}

Related

How come the if-statement is skipped when I am checking if a string is equal to a number?

I am trying to see if the user input is equal to a number, and if it isn't, then show a label saying, "Must be a number" and do not proceed until it is. I never learned about how to check if a string is equal to a number, so I searched it up and added it to my code, but it still doesn't work. Can someone look at it and tell me how I can fix my if-condition? Thank you in advance!
//variable that is used
var user_answer = getNumber("answer_input");
//Confirm your answer with clicking the button
onEvent("attackBttnForEquation", "click", function( ) {
if (isNaN("user_answer") === false){ //here is where I tried to use it, but it just skips the condition
showElement("mustBeNum_label");
setTimeout(function(){
hideElement("mustBeNum_label");
}, 1000);
}
setScreen("play_screen");
hideElement("fight_symbol");
checkAnswer();
checkLose();
});
This is what I tried based on a comment and it still did not work:
onEvent("attackBttnForEquation", "click", function( ) {
if (isNaN(user_answer) === true){ //I forgot to specify that user_answer is a variable, but I even set the condition to equal to true and it did the same thing as before.
showElement("mustBeNum_label");
setTimeout(function(){
hideElement("mustBeNum_label");
}, 1000);
}
Okay, with the answer I got, the "mustBeNum_label" shows, BUT when the user inputs an actual number, it still shows "mustBeNum_label".
//Confirm your answer with clicking the button
onEvent("attackBttnForEquation", "click", function( ) {
if (Number(user_answer)){
setScreen("play_screen");
hideElement("fight_symbol");
checkAnswer();
checkLose();
} else {
showElement("mustBeNum_label");
setTimeout(function(){
hideElement("mustBeNum_label");
}, 1000);
}
});
Try checking like this:
if (Number(user_answer) || user_answer == 0) {
// input is a number
} else {
// input is not a number
}
You can find out more here: Number - MDN
I would consider this a poor case for Number() since it will output NaN or a number.
Consider when you encounter 0: the conditional will run your else block since 0 is falsey.
Number.isInteger(Number(user_input)) may be a better solution since it will always output a boolean, and if it gets passed NaN will output false.
Shorter syntax would be Number.isInteger(+user_input)

Comparing two regex in Javascript and getting weird results

Can someone please explain this strange behavior in Javascript? When I do comparisons using the match() method I don't get the expected result.
var mat_1 = "wpawn";
var mat_2 = "wRook";
//compare both; do they have the same first letter?
alert(mat_1.match(/^\w/) + " seems equal to " + mat_2.match(/^\w/));
if (mat_1.match(/^\w/) === mat_2.match(/^\w/)) {
alert("They are really equal")
}
//another approach
if (mat_1[0] === mat_2[0]) {
alert("Yes! Equals")
}
match produces an array. You should really use an array comparison function, but for the sake of simple demonstration, try this - the first match value is selected and compared. All 3 alerts are triggered:
var mat_1 = "wpawn";
var mat_2 = "wRook";
//compare both; do they have the same first letter?
alert(mat_1.match(/^\w/)+" seems equal to "+mat_2.match(/^\w/));
if(mat_1.match(/^\w/)[0] === mat_2.match(/^\w/)[0]){alert("They are really equal")}
//another approach
if(mat_1[0] === mat_2[0]){alert("Yes! Equals")}
Match returns an array of matches:
String.prototype.match(pattern: Regex): Array<string>
Your first evaluation will always fail as you are comparing two arrays.
This is the correct way for what you are trying to achieve.
'myWord'.match(/^\w/)[0] == 'mIsTeRy'.match(/^\w/)[0]
Although if you wanna truly use the regex to check the first letter, I wouldn't recommend it. Too much overhead for something too trivial (just my two cents).
Have fun coding! :)
in the following lines of code you are checking the variables mat_1 and mat_2 for whether both the words starts with 'w', btw match() returns an array
if (mat_1.match(/^\w/) === mat_2.match(/^\w/)) {
alert("They are really equal")
}
you can try something like
if (["w"] === ["w"]) {
console.log("seems equal");
} else {
console.log("not equal");
}
for array comparison you can check this post
what you have to do here is
if (["w"][0] === ["w"][0]) { // match for the elements in the array
console.log("seems equal");
} else {
console.log("not equal");
}

Why redirect page doesn't work after 3 views from same device?

I use this javascript below to redirect a user to another web page if the user comes 3 times on the same webpage, but it's not working unfortunately.
var count = Number( localStorage.visitCount );
if(!isNaN(count) {
localStorage.visitCount = 1
} else {
localStorage.visitCount++
}
if( localStorage.visitCount === 3 ) {
window.location.replace('http://stackoverflow.com')
}
The redirection doens't work. Can someone tell me what I'm doing wrong? Thank you.
Try this:
var count = Number( localStorage.visitCount );
if(isNaN(count)) { // <-- you forget bracker here
localStorage.visitCount = 1
} else {
localStorage.visitCount++
}
if( localStorage.visitCount >= 3 ) {
window.location.replace('http://stackoverflow.com')
}
Also, as Eric J. said in this answer, it looks like as logical mistake in first if. It should be isNaN(count), not !isNaN(count). Explanation is in his answer.
Also, as gilly3 mentioned in his post you have to handle situation, when localStorage.visitCount greater then 3.
if( localStorage.visitCount > 3 ) {
// handler for this situation
}
The line
if(!isNaN(count) {
should probably be
if(isNaN(count)) {
You are not initializing count to 1 when it is Not-a-Number. Rather, you are attempting to increment it when it is Not-a-Number.
Also, you are missing a closing parenthesis (my corrected line accounts for that).
So, a couple minor things here.
Firstly, your syntax is off. It looks like you are missing a ")" in your if statement, as well as some missing semi colons.
Secondly, I also see some logic errors.
In your if statement, you want to set the count to 1 if it's not a number, so remove that "!". Otherwise it will do the opposite of what you want.
Also in your second if statement, you want to check if the number is greater than or equal to three, otherwise it will only redirect on the third occasion and not afterwards.
var count = Number(localStorage.visitCount);
if(isNaN(count)) {
localStorage.visitCount = 1;
} else {
localStorage.visitCount++;
}
if(localStorage.visitCount >= 3) {
window.location.replace('http://stackoverflow.com');
}
I count 3 or 4 issues:
Syntax error - You are missing a )
Logic error - Lose the ! before isNaN() (or keep it and use !isFinite())
Type comparison - The === zealots have convinced you to never use ==. In this case, you want == because localStorage variables are always strings and "3" === 3 returns false.
What happens on the 4th visit? If you want to redirect on the 3rd and subsequent visits, you should use >=.
It's working with the following code:
<script>
var count = Number( localStorage.visitCount );
if(isNaN(count)) { // <-- you forget bracker here
localStorage.visitCount = 1
} else {
localStorage.visitCount++
}
if( localStorage.visitCount == 3 ) {
window.location.replace('http://www.website.com')
}
if( localStorage.visitCount >= 3 ) {
window.location.replace('http://www.website.com')
}
</script>
Thank you guys!

How to check if a string contains a given string using jQuery

I Use this Code to check a char is contain in string if true checked checkbox but it always return true.why??
//it is mvc project and after execution it become like this:if ($("123:contains(1)"))
if ($("#Model.VillageAR.IncomeLocation.ToString():contains(1)"))
{
$('#IncomeLocation1').attr('checked', true);
}
I'm guessing you're really just looking for indexOf
if ( "#Model.VillageAR.IncomeLocation.ToString()".indexOf('1') != -1 ) {
$('#IncomeLocation1').prop('checked', true);
}

If else conditions in Javascript

I have topdatedata value as 222
I have these 3 conditions specified
if((topDateData<250)&&(topDateData>25))
{
alert('one');
}
else if((topDateData>300)&&(topDateData<300))
{
alert('Two');
}
else
{
alert('Three');
}
My questions is why is it getting the value as alert(3) and not alert(one)??
When explicitly setting the value to 222, I see 'one' get alerted: http://jsfiddle.net/Wvjfa/
You should debug your actual value ( alert(topDateData); if you like) and see if it really is what you think it is.
Beyond that, Matt Ball is right, your second condition is borked. Also lonesomeday and Kerry are right about your variable case not matching between your question and the posted code.
Javascript is case sensitive, is topdatedata = 222 or topDateData = 222?
it's much safer just to set one value - as you're second criteria looks dodgy
var topDateData = 222;
if(topDateData > 300)
{
alert('two');
}
else if(topDateData > 250)
{
alert('');
}
else if(topDateData > 25)
{
alert('One');
}
else
{
alert('Three');
}
start with the one that's hardest to satisfy (in this example the highest) and then work your way down. It's much easier to follow. Other than that it should work, as per the other comments on here
My guess is that you have a string.
var trueBool = '222' < '250'; //true
var falseBool = '222' > '25'; //false
To debug if topDateData is a String or not, do the following:
alert(topDateData + 1);//outputs '2221' if a string, and '223' if a number
Here's a fiddle showing the difference.
UPDATE:
I've tested alert(('222' < 250) && ('222' > 25)); and that outputs true. However, I'm not sure all JavaScript compilers will be smart enough to convert the string to a number first. You should run the same test and see if true is the output on your browser.
It looks like your topDateData variable contains a string value "222" instead of an integer.
You could try to cast to an integer this way:
topDateData = parseInt(topDateData);
...

Categories