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

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.

Related

How-To: In angularjs get length of field when ng-model equals undefined

I'm attempting, in my controllers.js, to validate a field that is not required, but has validation rules on it when something is entered in. And I cannot just disable the save button if the field is invalid. (per the user, and yes, I know this is very anti-Angular)
The field has a minlength of 2, and a maxlength of 100, and has an ng-pattern that it must pass... IF the user enters anything into it.
So, what I need to be able to do is read the length and value of that field... even when the ng-model for the field = undefined.
So, my method in the controllers.js:
var myPattern = /^[a-zA-Z0-9\ \-\.\,\']+$/;
if ((hasValue(vm.MyField) &&
(vm.MyField.length < 2 ||
vm.MyField.length > 100 ||
!myPattern.test(vm.MyField)))) {
vm.hasError_Overall = true;
vm.hasError_Certs = true;
errMsg += errMsg.length > 1 ? "<br />" : "";
errMsg += "MyField may only contain letters, numbers, spaces, and these symbols: - . , ', and be between 2 and 100 characters long.";
}
So, if the user enters, say, 1 character, and clicks the Save button, I want to be able to get into that if statement so I can display the message.
Just get rid of the first condition in the if statement, and handle the case of it being undefined before the if statement. As follows:
if(!hasValue(vm.MyField)){
vm.MyField="";
}
var myPattern = /^[a-zA-Z0-9\ \-\.\,\']+$/;
if (vm.MyField.length < 2 ||
vm.MyField.length > 100 ||
!myPattern.test(vm.MyField)) {
vm.hasError_Overall = true;
vm.hasError_Certs = true;
errMsg += errMsg.length > 1 ? "<br />" : "";
errMsg += "MyField may only contain letters, numbers, spaces, and these symbols: - . , ', and be between 2 and 100 characters long.";
}

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 !

Why is my code not able to recognize that a password contains characters?

I am making a login form. Before it submits, I check if all the fields are filled in. I also check if the password is longer than 7 characters and contains at least one number, at least one character, and no spaces. My current code keeps on telling me that I am missing a character no matter what I enter. This is the code:
if($("#password").val()==""){
error += "The password is required.<br>";
}
else if($("#password").val().length<8){
error += "Your password needs at least 8 characters.<br>";
}
else if($("#password").val().length >= 8){
var pass = $("#password").val().split("");
var hasNum = false;
var hasChar = false;
var hasSpace = false;
for(var i = 0; i < pass.length; i++){
if(pass[i] == " "){
hasSpace = true;
}
else if(Number(pass[i]) == NaN){
hasChar = true;
}
else if(Number(pass[i]) != NaN){
hasNum = true;
}
}
if(!hasChar){
error += "Your password must contain at least one character.<br>";
}
if(!hasNum){
error += "Your password must contain at least one number.<br>";
}
if(hasSpace){
error += "Spaces are not allowed in a password.<br>";
}
}
I first check for a space. Then I check if a character can be converted to a number. If not, then it must be a string. If it can be converted, it must be a number. Whatever I type in, it always says "Your password must contain at least one character". How can I fix this? I will give you more code if it is necessary.
The problem is that NaN compares unequal (via ==, !=, ===, and !==) to any other value, including to another NaN value:
NaN === NaN;// false
Number('S') == NaN; //false
Number(10) == NaN; //false
try to use isNaN() instead.

How to test the null value condition in 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

If/Else Statement Returning false positives

In my code, I have this if/else statement to deal with a situation in which the numbers and letters both return cont = false. I have tried running just this code, with the same result. Obviously, it should execute the code in the else statement. Does anyone have any ideas?
var input = prompt()
if (input == null || " ") {
//Cont determines whether or not to continue
console.log("cont = false");
var cont = false;
}else{
console.log("cont = true");
var cont = true;
}
Because that code is not how you check one input against two values.
if ( input == null || " " )
should be
if (input==null || input == " ")
input == null || " "
evaluates to (result of your comparison) || " ". Now since " " (a non-empty string) is a truthy value this always evaluates to true.
For order of evaluation -
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
Adding to the other replies which are all correct about the || operator and precedence.
Using == is not a good thing to do in most cases, not least because 0 == null etc - if you're checking if it's actually null or an empty string then something like this is safer:
if (input === null || input.trim() === "") {
...
This checks type as well as content, so won't be able to give false positives. though if input isn't a string it will complain.
Thank's so much! As a summary of all of the answers recieved so far:
The OR operator (||) is comparing input == null to " ", the latter of which always evaluates to true
=== is better than ==
Thanks again for all the help and support!

Categories

Resources