Hi im having difficulties in this code, i think my if else conditions are wrong.
When you run the program, if the user inputs nothing, it sends 'list-group-item-danger' which is the first if statement, then if the user inputs both NAME and PLACE, it sends 'list-group-item-success'. Both are correct.
if the user input at least one input (NAME or PLACE) it sends 'list-group-item-success' also which is wrong, because it doesn't satisfy the condition on the 2nd if statement (PLACE and(&&) NAME), it should be on the last statement which it sends 'list-group-item-warning'
var obj = {}; db.all("SELECT * FROM f41 WHERE id = ?",[id], function(err,rows){ if((rows[0].NAME == null || rows[0].NAME == '') && (rows[0].PLACE == null || rows[0].PLACE == '')) { obj.f41='list-group-item-danger'; } else if((rows[0].NAME != null || rows[0].NAME != '') && (rows[0].PLACE != null || rows[0].PLACE != '')) { obj.f41='list-group-item-success'; } else { obj.f41='list-group-item-warning'; } res.send(obj); });
In my understanding, issue is here:
(rows[0].NAME != null || rows[0].NAME != '')
If row[0].NAME
is null
, its not equal to ""
and vice-versa. Hence it will return true.
You can try
!(rows[0].NAME == null || rows[0].NAME === '')
You can also try to create a utils function isEmpty
var obj = {};
db.all("SELECT * FROM f41 WHERE id = ?", [id], function(err, rows) {
if (isEmpty(rows[0].NAME) && isEmpty(rows[0].PLACE)) {
obj.f41 = 'list-group-item-danger';
}
else if (!isEmpty(rows[0].NAME) && !isEmpty(rows[0].PLACE)) {
obj.f41 = 'list-group-item-success';
} else {
obj.f41 = 'list-group-item-warning';
}
res.send(obj);
});
function isEmpty(v){
return v === null || v.toString().trim().length === 0
}
You can improve your conditions like this
if(rows[0].NAME && rows[0].PLACE) {
obj.f41='list-group-item-success';
} else if(!rows[0].NAME && !rows[0].PLACE) {
obj.f41='list-group-item-danger';
} else {
obj.f41='list-group-item-warning';
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.