Why is this javascript if condition not working as expected? - javascript

I am doing a comparison on dates in javascript. In this case date1 is empty "" and I can see the same in firebug. As per the code below, the first alert shouldn't be called because date1 == "", but for some reason the alert alert(" This is called...."); is invoked. What is wrong here?
if(date1 != null || date1 != ""){
if( (date1 != null || date2 != "") && (date1 < date2)){
alert(" This is called....");
break;
}
else{
alert(" That is called....");
break;
}
}
The above if condition is inside a for loop, hence the break.

I think you mean to be using && instead of || in your first comparision to make sure that both conditions are true and I think you have typo where you're using date1 instead of date2 in the second test. Further, you can just use if (date1) to simultaenously rule out null and "" and undefined and 0 and NaN and any other falsey value.
I think you want something like this:
if (date1) {
if(date2 && date1 < date2) {
alert(" This is called....");
} else {
alert(" That is called....");
}
break;
}
If what you're really trying to do is make sure that date1 and date2 are legal numbers, then I'd suggest you do this:
if (typeof date1 == "number") {
if(typeof date2 == "number" && date1 < date2) {
alert(" This is called....");
} else {
alert(" That is called....");
}
break;
}
Or, if they're supposed to be Date objects, then you can test for that:
if (date1 instanceof Date) {
if(date2 instanceof Date && date1 < date2) {
alert(" This is called....");
} else {
alert(" That is called....");
}
break;
}

It looks correct to me. This statement evaluates to true because of the OR (||), since date1 is not null:
if(date1 != null || date1 != ""){
(it simplifies to if (true || false) { which is always true.
and the following statement evaluates to true as well because "" is not equal to null, and, presumably, date1 is less than date2:
if( (date1 != null || date2 != "") && (date1 < date2)){

I want to suggest you this syntax
if( (x==5) || (x==6) || (x==7) || (x==8) )
this is best answer for checking OR condition using JavaScript and JQuery.

date1 is empty ""
Look at this condition:
date1 != null || date1 != ""
date1 is != null, the second term (date1 != "") isn't even evaluated because the first one passes - and the whole expressions evaluates to true.
Furthermore this condition:
date1 != null || date2 != ""
is also met (see above) - did you mean date2 != null this time? Nevertheless your This is called is displayed. BTW break has no sense in this context.
Finally you might consider simply:
if(date1) {
Not 1:1 equivalent, but pretty close.

Maybe that's a case where you should think about readability of your code. Here is my interpretation of your code:
if(!isBlank(date1){
if(dateXIsSmallerThanDateY(date1, date2))
alert(" This is called....");
else
alert(" That is called....");
}
function isBlank(date) {
return date != null || date != "";
}
function dateXIsSmallerThanDateY(x,y) {
return (x != null || y != "") && (x < y);
}
do you see a problem in dateXIsSmallerThanDateY? I can see one. What is that supposed to mean: x != null || y != ""? Probably it should read y != null || y != "", which in turn can be shortend to !isBlank(y).
Additionally the isBlank function does not check for beeing blank. Look what it does: It thinks that your date is blank if it is either not null or if it is not an empty string. Ok, maybe that is hard to read, so reverse this method:
function isNotBlank(date) {
return date == null && date == "";
}
Positive comparisions are way easier to read. Do you see what is happening here? Can date be null and "" AT THE SAME TIME? No? Good. Than I guess you know what to do:
function isNotBlank(date) {
return date != null && date != "";
}
Or in reverse:
function isBlank(date) {
return date == null || date == "";
}

Related

JS operator on document.getElementById gives unexpected result

I am using this JS code without any issues:
if(document.getElementById('add_calc_srt_gew').value.length != '' &&
document.getElementById('add_calc_dia_inner').value.length != '' &&
document.getElementById('add_calc_dia_out').value.length != '' &&
document.getElementById('add_breedte').value.length != '') {
// do something }
I need to add one more check. When add_calc_dia_out is larger then add_calc_dia_inner
So I have changed the JS to:
if(document.getElementById('add_calc_srt_gew').value.length != '' &&
document.getElementById('add_calc_dia_inner').value.length != '' &&
document.getElementById('add_calc_dia_out').value.length != '' &&
document.getElementById('add_breedte').value.length != '' &&
(document.getElementById('add_calc_dia_out').value > document.getElementById('add_calc_dia_inner').value)) {
// do something }
But the code that should be triggered is not triggered. Also no errors are shown. What is the correct way to be sure that add_calc_dia_out is larger then add_calc_dia_inner ?
Here is a DRY version
const num = str => isNaN(str) || str.trim() === "" ? 0 : +str;
const srt_gew = num(document.getElementById('add_calc_srt_gew').value),
dia_inner = num(document.getElementById('add_calc_dia_inner').value),
dia_out = num(document.getElementById('add_calc_dia_out').value),
breedte = num(document.getElementById('add_breedte').value);
if (srt_gew && dia_inner && dia_out && breedte && dia_out > dia_inner) { /* do something */ }
You are compare 2 number in string. It will cause unexpected behavior like '9' > '11'. You have to parseInt() them first. Try this:
... && parseInt(document.getElementById('add_calc_dia_out').value) > parseInt(document.getElementById('add_calc_dia_inner').value)) {
Also, you should check if it's a valid number or not before doing the compare:
!Number.isNaN(document.getElementById('add_calc_dia_out').value) && !Number.isNaN(document.getElementById('add_calc_dia_inner').value))

Cannot read property 'split' of undefined using calendar

I am working on calendar with js in my project for availabilities it works correctly. but when I have a record which has a start date equal an end date.
for add event to my calendar i'm using this push:
listDate.push({startDate :strDate, endDate : enDate});
in my script datetimepicker this is function isAvailable
isAvailable: function(date, month, year) {
for (var i in this.unavailable) {
var book_date = this.unavailable[i].startDate.split("-");
if (book_date.length !== 3) {
return false;
} else if (
(book_date[0] == "*" || book_date[0] - year === 0) &&
(book_date[1] == "*" || book_date[1] - month === 0) &&
(book_date[2] == "*" || book_date[2] - date === 0)
) {
return false;
}
}
return true;
}
I get this issues: Cannot read property 'split' of undefined in this line
var book_date = this.unavailable[i].startDate.split("-");
please any help thanks for you
this.unavailable[i].startDate is undefined. Does listDate reference this.unavailable or is it a different array? Put a breakpoint or use console.log to inspect the contents of this.unavailable in the isAvailable function.
The code does not give me any error in my console. Can you try storing the value of unavailable in a separate variable and use that variable instead. This might help.
isAvailable: function(date, month, year) {
var unavailable = this.unavailable;
for (var i in unavailable) {
var book_date = unavailable[i].startDate.split("-");
if (book_date.length !== 3) {
return false;
} else if (
(book_date[0] == "*" || book_date[0] - year === 0) &&
(book_date[1] == "*" || book_date[1] - month === 0) &&
(book_date[2] == "*" || book_date[2] - date === 0)
) {
return false;
}
}
return true;
}
You are using a for in loop to iterate through an array - for in loops should only be used on objects. You should use a plain for loop or forEach
isAvailable: function(date, month, year) {
for (var i = 0; i < this.unavailable.length; i++) {
var book_date = this.unavailable[i].startDate.split("-");
if (book_date.length !== 3) {
return false;
} else if (
(book_date[0] == "*" || book_date[0] - year === 0) &&
(book_date[1] == "*" || book_date[1] - month === 0) &&
(book_date[2] == "*" || book_date[2] - date === 0)
) {
return false;
}
}
return true;
}

if else statement reverse

the result I want is second if else statement if code not in the list then alert, I don't get why the first if else statement fail, I thought that just reverse second if else statement ?? do I misunderstand some thing??
https://jsfiddle.net/e6qohvhc/
var code = '500';
if (code != '400' || code != '401' || code != '500') {
console.log('true'); // I don't want it alert here
}
if (code == '400' || code == '401' || code == '500') {
// I have to always leave this empty line ...
} else {
console.log('second true');
}
This has to do with De Morgan's laws:
If you want to invert a statement you have to invert every operator.
!a becomes a, b becomes !b, ||becomes &&, && becomes ||.
So the inversion of your second if would be something like
(code != '400' && code != '401' && code != '500')
You may need to review the Morgan's laws.
Basically, if you want to negate (a || b || c) you need to use (!a && !b && !c)
Hope it helps,
if(code != '400' || code != '401' || code != '500'){}
always will be true because a variable cant be equal to multiple values
The problem is ||
First if statement for 500 is always true, that's why you are having problem/
Do it in this way and it should work the way you wanted it (check it out in your fiddle);
var code = 500;
alert(code);
console.log(code);
if (((code !== 400) || (code !== 401)) && (code !== 500)) {
console.log('true');
alert("123");
}
else if ((code == 400) || (code == 401) || (code == 500)) {
alert("456");
} else {
console.log("second true");
alert("else");
}

checking the time with Date.getSeconds() is not working

I'm using JavaScript to check the user's time every 600ms (so my code runs once a second, but the time is unlikely to shift due to deviation in the setInterval method). My code looks like this:
setCorrectingInterval(function(){
needs_run = false;
switch(date.getDay()) {
case 1:
if(date.getHours() == "8" && date.getMinutes() == "50" && date.getSeconds() == "0") {
next = array.ItemA;
needs_run = true;
}
break;
[abridged, all other ifs and cases are identical except the times and days]
}
if(needs_run == true) {
alert("foobar");
}
}
(setCorrectingInterval is a custom function designed to correct the deviation from setInterval as much as possible)
My issue is that I never get alert("foobar"). I've used console.log() and done some trial-and-error, what I've narrowed it down to is the date.getSeconds() == 0 call. I've tried using (date.getSeconds() <= "5" && date.getSeconds() >= "0"), to no avail. The desired outcome is that, in this case, at 8:50AM on Monday, I get an alert, once.
When I omit the date.getSeconds() call, it works fine and dandy.
My guess is that something with your setCorrectingInterval() function or the date variable is wrong. It works fine with new Date().
;window.setInterval(function(){
var tDate = new Date()
console.log(tDate.getDay(), tDate.getHours(), tDate.getMinutes(), tDate.getSeconds())
needs_run = false;
switch(tDate.getDay()){
case 1:
if(tDate.getHours() == "8" && tDate.getMinutes() == "50" && tDate.getSeconds() == "0"){
//next = array.ItemA;
needs_run = true;
}
break;
case 5:
//No need to compare to string
//if(date.getHours() == "13" && date.getMinutes() >= "50" && date.getSeconds() >= "0") {
if(tDate.getHours() == 13 && tDate.getMinutes() >= 50 && tDate.getSeconds() >= 0){
//next = array.ItemA;
needs_run = true;
}
break;
}
if(needs_run == true){
console.log('foorbar') //alerts can be bad.
}
}, 1000);
More than likely, date is not what you expect it to be. I suppose the following would be more appropriate for your case:
var date = new Date();
switch(date.getDay()) {
...
You commented:
setCorrectingInterval is a custom function designed to correct the
deviation from setInterval as much as possible
What does that even mean? What do you mean by "correct the deviation from setInterval"?

jQuery function for check textbox

I’d like use jquery function that validate a input field. This input field must be used for entering 11 digit numbers that start with 0.
I tried some function but doesn’t work!
function check(mob) {
var firstnum = mob.substring(1);
alert(firstnum);
if (firstnum != "0" || mob.lenght != 11)
return false;
else
return true;
}
function check(mob) {
return mob.substring(0, 1) == '0' && mob.length == 11;
}
String Method Reference
If you want to check is it 11 digit, you should use RegExp
function check(mob) {
return mob.match(/^0\d{10}$/) != null;
}
You need to use .charAt(0) to get the first character of a string. .substring(1) will return the rest of the string minus the first character.
"01234567890".substring(1) = "1234567890"
"01234567890".charAt(0) = "0"
"01234567890".length = 11 (assuming that you have spelled "length" correctly in your code)
Edit: Since you also need to check for digits, you could use a regular expression to verify this (although the whole check could also be done with a regex)
The completed function could therefore be simplified to just:
function isValidMobile(mobileNumber) {
return mobileNumber.charAt(0) == 0 && mobileNumber.length === 11 && /^\d+$/.test(mobileNumber);
}
Or without the regex
function isValidMobile(mobileNumber) {
return mobileNumber.charAt(0) == 0 && mobileNumber.length === 11 && !isNaN(mobileNumber);
}
if (firstnum >= 1 || mob.lenght <= 11) //lenght spell wrong
change to
if (firstnum >= 1 || mob.length<= 11)
you can give it a try
function check(mob) {
var num = parseInt(mob);
if (mob+'' == '0'+num && mob.length == 11)
return true;
else
return false;
}
here what I am doing is that parseInt will give you exact same number without 0 if all characters are numbers, so in the condition I am just adding 0 in starting and checking with mobile number , it will do 2 validation in once , all are number starts with 0 and next validation is for length
Try using a simple regex as below
function check(mob) {
return /^0\d{10}$/.test(mob)
}
function check(mob) {
if(!isNaN(mob)){ // or use parseInt
var firstnum = mob.charAt(0);
alert(firstnum);
if (firstnum != "0" || mob.length != 11) {
return false;
} else {
return true;
}
}
}

Categories

Resources