check JavaScript variable null or not? - javascript

Iam using following lines of code to check whether the JS variable 'userName' is null or not.
But am always getting alert "not empty"
Please check my onready method:
$("document").ready(function (){
var userName = "";
if (userName == undefined || userName == null) {
alert('empty');
} else {
alert('not empty');
var div = document.getElementById('title b');
div.innerHTML = div.innerHTML + ',';
}
});

You need typeof keyword to check it's type. !userName will take care of the rest, like null or empty values.
if ( typeof userName === 'undefined' || !userName ) {
alert('empty');
}

You're setting var userName to "". It will never be null.
Declare your variable as var userName;, instead of var userName = "";
However, unless you actually do something with userName, the if / else will be pretty pointless.

No your variable is neither undefined nor null.
What you could do though is this replace this line
if (userName == undefined || userName == null) {
by this line
if (!userName) {

Empty string is not null nor undefined.
You can check using the ! operator:
if (!userName) {
// Do the stuff
}
For completeness:
!"" == true
!null == true
!undefined == true
!"hi" == false
Note that:
!0 == true
!1 == false
!"0" == false
!"1" == false

Try
var userName = "";
if (userName.length < 1) {
alert('empty' +"\n"+ userName.length);
} else {
alert('not empty');
var div = document.getElementById('title b');
div.innerHTML = div.innerHTML + ',';
}

Related

error in javascript conditional statement

I am facing an issue in javascript. if key value is true they stop it return true whereas if key value is false they shows Error.
Problem: they don't read the condition number or name value in if body. if key value is true they terminate.
How should i handle this condition? that they should also read the condition number or name value in if body.
can i use else if statement here ?
var key = $('#key').val().trim();
if(key != "" ){
return true; //value is true if value is true they stopped it
}
if(key === ''){
showError(); //this field is required
return false;
}
//if key value is true they don't execute my number or name condition
if ( $('#number').val().trim() === '' || $('#name').val().trim() === '' )
{
if ($('#number').val().trim() === '') {
showError(); //this field is required
}
if ($('#name').val().trim() === '') {
showError(); //this field is required
}
return false;
}
else{
return true; //always return true
}
how can i do? anyone help me?
Not sure if this is what you wanted. Have a look. The code continues after checking key.
var key = $('#key').val().trim();
if(key === ''){
showError(); //this field is required
let keyStat = false;
}
//if key value is true they don't execute my number or name condition
if ( $('#number').val().trim() === '' || $('#name').val().trim() === '' || keyStat === false) {
if ($('#number').val().trim() === '') {
showError(); //this field is required
}
if ($('#name').val().trim() === '') {
showError(); //this field is required
}
if (!keyStat) {
showError(); //this field is required
}
return false;
}
else{
return true; //always return true
}
when you call return statement your function will exit,only code before the return statement will run
Example:
function bar(){
var key = 12
if(key === 12){
console.log("only code before the return statement will run")
return true; // when you call return your function will exit
}
console.log("this will be terminated")
}
click me

Why does my function not return the error string?

I have function below. It does what it needs to except that it does not return the error string I want.
It always returns "".
I've put breakpoints and seen it step into each error case, but it doesn't return there. It returns at the end of the function.
I'm lost, I'm sure I'm making a really stupid mistake but I don't get it...
Save me the few hairs I have please :)
public validatePanel = () => {
this.Queries().forEach(function(q, i) {
if(q.from() == "" || q.from() == null || q.from() == undefined) {
return "Please select a database";
}
if(q.select().length > 0) {
q.select().forEach(function(s, j) {
if(s.selectoption() == "" || s.selectoption() == null || s.selectoption() == undefined){
return "Please select a stat to show";
}
});
}
if(q.where().length > 0) {
q.where().forEach(function(w, j) {
if(w.whereoption() == "" || w.whereoption() == null || w.whereoption() == undefined){
return "Please select a filter to filter on";
}
if(w.wherevalue() == "" || w.wherevalue() == null || w.wherevalue() == undefined) {
return "Please select a value for your filter";
}
});
}
});
return "";
}
As pointed out by Alex Bykov, your forEach function is not causing a return.
Your question on why not, per the MDN
The return value of the function is undefined
Return
value undefined.
Which means nothing you can do will generate a return value you can use. Also per the MDN there is no way to stop or break the loop other than throwing an exception.
There is no way to stop or break a forEach() loop other than by
throwing an exception. If you need such behavior, the forEach() method
is the wrong tool, use a plain loop instead. If you are testing the
array elements for a predicate and need a Boolean return value, you
can use every() or some() instead. If available, the new methods
find() or findIndex() can be used for early termination upon true
predicates as well.
Which means you will need to throw your exception in the forEach loop and then catch the exception and return the string like below
(unless you use a normal for loop then you can do whatever you please)
try {
this.Queries().forEach(function(q, i) {
if(q.from() == "" || q.from() == null || q.from() == undefined) {
throw "Please select a database";
}
if(q.select().length > 0) {
q.select().forEach(function(s, j) {
if(s.selectoption() == "" || s.selectoption() == null || s.selectoption() == undefined){
throw "Please select a stat to show";
}
});
}
if(q.where().length > 0) {
q.where().forEach(function(w, j) {
if(w.whereoption() == "" || w.whereoption() == null || w.whereoption() == undefined){
throw "Please select a filter to filter on";
}
if(w.wherevalue() == "" || w.wherevalue() == null || w.wherevalue() == undefined) {
throw "Please select a value for your filter";
}
});
}
});
}
catch(err) {
console.log(error);
}

Simple javascript form validation won't return true

I created this function where it checks for multiple textboxes if they have values onsubmit. Basically it is a javascript form validator. When there are empty textboxes, form shouldn't submit and alert the user that there are required fields. Now, this works for me perfectly, however, when there are values already and the form is submitted, it still doesn't submit even though it should. I created an if statement to check if the errorString is empty or null, if it is, the form should submit but what happens is that it alerts the user with a blank string. I think the code is still going inside the if(errorString!=null || errorString=="") statement even though it shouldn't.
Thanks in advance
Please see my code below:
function validateForm()
{
var txtTitle = document.forms["actionStepsForm"]["txtTitle"].value;
var txtRequestor = document.forms["actionStepsForm"]["txtRequestor"].value;
var txtReprocessingRequest = document.forms["actionStepsForm"]["txtReprocessingRequest"].value;
document.getElementById('rowCount').value = counter-1;
var errorString = "";
if (txtTitle==null || txtTitle=="")
{
errorString += "Title field is required. \n";
}
if (txtRequestor==null || txtRequestor=="")
{
errorString += "Requestor field is required. \n";
}
if (txtReprocessingRequest==null || txtReprocessingRequest=="")
{
errorString += "Reprocessing request FR is required. \n";
}
if (errorString!=null || errorString!="")
{
alert(errorString);
return false;
}
else
{
return true;
}
}
//implementation if HTML form
<form name="actionStepsForm" id="actionStepsForm" action="add_reprocessing.php?action=add" method="POST" onsubmit="return validateForm()">
errorString can never be null because you've initialized it with "" so you can remove the condition "errorString != null".
It should become
if (errorString!="")
{
alert(errorString);
return false;
}
else
{
return true;
}
I think the correct condition should be
if (errorString != null && errorString != "")
otherwise the engine evaluated the 'errorString != null' condition, which evaluates to true (since errorString is "" and not null), and enter the code block.
Change
if (errorString!=null || errorString!="")
to
if (errorString!=null && errorString!="")
You have two 'not' statements that cancel each other out (one must always be false). Change it to:
if (errorString!=null && errorString!="")
{
alert(errorString);
return false;
}
else
{
return true;
}
The wrong line is the one everyone pointed out:
if (errorString!=null || errorString!="")
But I would like to point that you don't need to check for errorString!=null because you already created the variable as an empty string in the beginning of your code:
var errorString = ""; //created errorString as empty string
Therefore it will never actually be null, because you never set it as null anywhere (that is, you never set it as errorString = null).
If there are no errors, it will be an empty string always. So this will suffice:
if (errorString!="") //if errorString is different than what we created at `var`
{
alert(errorString);
return false;
}
else
{
return true;
}
Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var errorString; //The Values can be like as null,blank,undefined,zero you can test
if(!(!(errorString))) //this condition is important
{
alert("errorString"+errorString);
}
else
{
alert("errorStringis "+errorString);
}
}

Check two variables for undefined

JS:
var ctoken = req.cookies.user;
var stoken = req.session.passport.user;
if(ctoken === 'undefined' || stoken === 'undefined'){
return res.send('invalid token');
}else{
if (ctoken.split('_')[0] !== stoken) {
return res.send('invalid token');
}
}
At
ctoken.split('_')[0]
an error is thrown :
cannot call split of undefined.
Why? This should not happen because of the if condition.
Remove the quotes :
if (ctoken === undefined || stoken === undefined) {
Maybe you were confused by a trend during which some programmers recommended to test using
if (typeof something === 'undefined') {
But the best test is to simply compare with undefined.

Some problem with jquery form

This my code:
$(document).ready(function() {
$('.submit').click(function() {
var answer_text = $("#answer_text").val();
if (answer_text === '' || undefined === $("input[name='answer[scale]']:checked").val()) {
alert('error!!');
return false;
}
else {
alert('yeah! cool baby!');
}
}
});
Problem: jQuery doesn't see the ||. I don't know what to do. I tried to do something like:
if
else if
else
or
if
else
if
else
Don't know what to do. please help me, maybe some error and mistakes with OR operator? or what?
To know if no checkbox was checked just use the length, no need to mess with the value:
if (answer_text === '' || $("input[name='answer[scale]']:checked").length === 0) {
//answer text is empty and no answer scale checkbox was checked
}
i guess what you wanted to do is
if (answer_text === '' || $("input[name='answer[scale]']:checked").val()==="undefined"){
you have got the operands on the wrong side of the operator
Try to wrap it in proper braces and check.
if ((answer_text === '') || (undefined === $("input[name='answer[scale]']:checked").val()))
$(document).ready(function() {
$('.submit').click(function() {
var answer_text = $("#answer_text").val();
if (answer_text == ''){
if ( undefined === $("input[name='answer[scale]']:checked").val()){
alert('error!!');
return false;
}
else{
alert('yeah! cool baby!');
}
}
else{
alert('yeah! cool baby!');
}
}
}
This is not the fastest way but it will do it...

Categories

Resources