How to test the null value condition in Javascript? - javascript

Below is the code,
<p id="sayHello"></p>
<script type="text/javascript">
var yourName = window['prompt']("What is your name?");
if (yourName != null) {
window['document']['getElementById']("sayHello").innerHTML = "Hello " + yourName;
} else {
window['alert']("Please enter your name next time");
}
</script>
for which, else block need to get executed based on the input given in prompt.
What should be the input in prompt box to test null value of primitive type Null?

When you click cancel on the prompt box the else block will get executed.

Per the MDN window.prompt docs:
If the user clicks OK without entering any text, an empty string is returned.
So really you want to check if (yourName !== null && yourName !== "") since the prompt is really returning the empty string (thus causing your else clause to be executed incorrectly since it's passing the not null check).

I think you actualy looking for empty string.Also null is a primitive value & null represent an "empty" value, that is no object value is present.
So to check null we can use
if(somVar === null && typeof somVar ==='object')
So you can arrange you code as
var yourName = window['prompt']("What is your name?");
if (yourName === null & typeof(yourName) ==='object') {
alert("Please enter your name next time");
} else {
document.getElementById("sayHello").innerHTML = "Hello " + yourName;
}
Also note this will ONLY test for null and will not pass for "",undefined,false,0 & NaN.
Beside is there any reason to use
window['document']['getElementById']("sayHello")
when it can be done like this
document.getElementById("sayHello").innerHTML
If you are checking for empty string , then you also have to validate that input is not empty
DEMO

Related

How to grab empty value from document.getElementByID('something').value

I'm want to have a conditional if the value is empty. But when I click on the button now, and I have value on either of the fields, it's prompts the message to enter a value. Thanks!
I tried to make them equal to an empty string
let fieldValue1 = document.getElementById('something1').value;
let fieldValue2 = document.getElementById('something2').value;
if (fieldValue1 == " " && fieldValue2 == " ") {
document.getElementById('someDiv').innerHTML = "Please enter either fieldValue1 or fieldValue2"
}
The message should prompt only if both field values are empty.
fieldValue1 == " " will only work if there is 1 space in the field (like if you pressed the space bar once).
You can do:
fieldValue1 == "" && fieldValue2 == ""
...which means "is equal to an empty string". Or, since an empty string is "falsy" in JavaScript, you can just do:
!fieldValue1 && !fieldValue2
If you want the message to prompt only if both fields are empty, couldn't you just just check like this:
if(!fieldValue1 && !fieldValue2)
{
document.getElementById('someDiv').innerHTML = "Please enter either fieldValue1 or
fieldValue2"
}
The problem is that the string you are checking for is one space, not an empty string. You need to check for '', not ' '.
Just a fix for your codes.
let fieldValue1 = document.getElementById('something1').value;
let fieldValue2 = document.getElementById('something2').value;
if (fieldValue1 === "" && fieldValue2 === "") {
document.getElementById('someDiv').innerHTML = "Please enter either fieldValue1 or fieldValue2"
}
You just need to check for empty fields, which "" with no space in between is needed.

Validate that multiple Prompts have a value

I´m trying to write a simple test where I ask for name and age in separate Prompts. I´d like to validate user really adds a value in both prompts.
What´s the best way to do this validation without duplicating code?
When I click "OK" with no value, it does not ask me to add a value
function showInfo() {
//Asking for name in a prompt
var name = prompt("Name: ","");
//Checking if it is null or empty
if (name == null || ""){alert("Please enter your name");}
//Same for age
var age = prompt("Age: ","");
if (age == null || ""){alert("Please enter your age.");}
}
Also, noticed that "null" is to check the "Cancel" button, but I was able to test that if you click "Cancel", and click "Cancel" again, it does not ask for a value. How can I solve this issue?
You if condition is wrong. You should use
if (name === null || name === "") {
//you code here
}
And If you like to show prompt continusly unless user enters input below code will work:
function showInfo() {
while(1) {
//Asking for name in a prompt
var name = prompt("Name: ","");
if (name === null || name === ""){alert("Please enter your name");}
else break;
}
console.log("Name= "+name);
while(1) {
//Same for age
var age = prompt("Age: ","");
//Checking if it is null or empty
if (age === null || age === ""){alert("Please enter your age.");}
else break;
}
console.log("Age ="+age);
}
showInfo();
You could put it in a loop to ask again. Here I'm using !name to check for the
"truthyness" of name. null and an empty string are both "falsy" so, !name
will return true for them, a non-empty string is truthy, so !name will
return false for them.
function ask (msg, errMsg) {
var name;
do {
name = prompt(msg);
//Checking if it is null or empty
if (!name) {
alert(errMsg);
}
} while (!name);
return name;
}
function showInfo() {
var name,
age;
name = ask("Name:", "Please enter your name");
age = ask("Age:", "Please enter your age.");
}
showInfo();
That said, unless this is just a prototype or a small personal project only you
will use, don't do it this way! Sticking the user in a loop prompt will
frustrate most people. Most modern browsers include a "Don't show me this again"
check box. I'm not sure what would happen if the user checks it, the browser
might continue in an infinite loop and lock up or crash.
Instead it would be better to do it with a form on the page:
var elShowInfo = document.getElementById('show-info'),
elName = document.getElementById('name'),
elAge = document.getElementById('age'),
elOut = document.getElementById('output');
function showInfo (ev) {
// stop the form from submitting
ev.preventDefault();
var name = elName.value,
age = elAge.value;
if (name && age) {
// do something with name/age
elOut.textContent = name + ' is ' + age + ' years old.';
}
}
elShowInfo.addEventListener('click', showInfo, false);
<form>
<label for="name">Name:</label> <input id="name" placeholder="Please enter your name">
<label for="age">Age:</label> <input id="age" placeholder="Please enter your age">
<button id="show-info">Show info</button>
</form>
<div id="output"></div>
Every time the Show Info button is pressed it checks for the data once and then does something with it if it is there; otherwise it does nothing.
One thing to note, both prompt and the .value property of an element return strings so if you are going to use age to do some sort of calculation you will need to convert it to a number either using parseInt, age = parseInt(age, 10) or an unary +, age = +age;.
Further reading:
Truthy and Falsy: When All is Not Equal in JavaScript
Introduction to the DOM
#Arshad answer adds more clarity.
on a side note, the reason why the || didn't work is the order of evaluation.
if (age == null || "") --> evaluated as
if ((age == null) || "") --> true on Cancel, false on Ok
Hope this helps !

null escaped in nodejs

I console.log("var = " + JSON.stringify(result.something));
I got var = null
but when I do
if(result.something !=null || result.something != ''){
console.log('enter')
}
it print enter also. I wonder why is that happening, I also tried result.something != 'null', it still go into the if statement.
Your variable is null, here's why:
1. (result.something !=null) : returns false
2. (result.something != '') : returns true
Since you've used an OR operator, program control is going to go inside the if block if either of the condition is true.
As your 2nd condition is evaluating to be true, it's going inside of the if block.
From javascript MDN:
null : "an empty value" i.e no object value present
null value is different from an empty string. So something like if(null ==== " ") will return false
your if statement always true because
the result.something is null AND it is not an empty string null != ''
:)

jQuery live validation

I'm trying to create a live validation script for a form. I've somewhat got it, I think anyway...but the error message comes up when there is text in the field as opposed to when there is no text. I'm sure I'm doing something stupid wrong, I'm pretty sure I have the if values right, value == '' is if value is nothing, value !== '' is if value is not nothing, right? Gah, maybe it's the on/change thing I should change? Hope you can help. Thank you.
http://jsfiddle.net/Vjwxs/3/
$(document).ready(function () {
$('#name').on('change', function() {
var name = $("#name").val();
if (!this.value == '') {
$("#errorname").fadeIn();
$('#errorname').css("display", "inline-block");
$('#errorname').css("color", "#838383");
$('#errorname').css("background-color", "#fff568");
}
else if (!this.value !== '' ) {
$("#errorname").fadeOut();
$('#errorname').css("display", "none");
}
});
});
Read your if conditions out loud. That should help you realise where the problem is:
if (!this.value == '') { /* Show the error */ }
"If not this value is equal to an empty string". Or, in a more understandable form, "If this value is not equal to an empty string". You actually want to show the error "if this value is equal to an empty string".
if (!this.value !== '' ) { /* Hide the error */ }
"If not this value is not equal to an empty string". And again, more readable, "If this value is not not equal to an empty string". You actually want to hide the error "if this value is not equal to an empty string".
Your code will work if you remove the first negation from both conditions.

What type of form input to be expected from a user that would yield null in javascript?

I'm not sure if my question is clear enough, but consider the following function:
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "") {
alert("First name must be filled out");
return false;
}
}
What I don't get is "null"; I understand that an empty string "" indicates nothing has been inputted, but what would be the type of input by a user that would imply null?
The value attribute of an input element returns a string, which will contain the text inputted by the user, or otherwise it will be empty (""). There is not and should not be a reason to check for null in the condition because a string (empty or not) can never be equal to null.

Categories

Resources