test if two variables holds some data javascript - javascript

I define variables from two input fields - and wants to test if something was actually entered in both fields and then break if more than one field is filled.
I think the 'undefined' tricks me when setting the var's to .value - even though they don't contain data.
var value1 = document.getElementById('filegroup').value;
var value2 = document.getElementById('new_filegroup').value;
if(value1 !== undefined && value2 !== undefined )
{
alert("You must only fill one filegroup!")
return false;
}
Right now I'm being alerted even though I don't fill in anything.

Assuming document.getElementById('filegroup') is a form input of some type, the value will return a empty string when there is no value. Try:
var value1 = document.getElementById('filegroup').value;
var value2 = document.getElementById('new_filegroup').value;
if(value1 && value2) { // checks both values have something
alert("Both values have something")
}
if(value1 || value2) { // checks for at least one value
alert("one of them does")
}
N.B. if the values do come from a input, then a value of 0 will be a string, and seen as truthy. However the number 0 will be falsey.

Related

How to check in Javascript whether variables are null or not? And how to make a message pop up when the variables are null?

I need to solve these two issues.
Here's the code:
function check() {
var Name=document.getElementById("Name");
var Surname=document.getElementById("Surname");
if (Name==null && Name="" || Surname==null && Surname="") {
alert("Enter the name or surname");
return false;
}
return true;
}
Basically, what this part should do is that:
It should fetch the value of "Name" and "Surname" variables
It should check whether the value of those two variables are null or not
If the value is indeed null, then a message stating "Enter the name or surname" should pop up and notify the user to enter his/her name/surname.
In order to get the values, you should do:
var Name=document.getElementById("Name").value;
var Surname=document.getElementById("Surname").value;
And to check if the user entered both:
if (Name==null || Name=="" || Surname==null || Surname=="")
You should do the nullchecking using typeof, the returning dom-element is also an object so == "" is not going to work.
function check(){
var Name=document.getElementById("Name");
var Cogn=document.getElementById("Surname");
if (typeof Name === null || typeof Surname === null )
{
alert("Enter the name or surname");
return false;
}
return true;
}
Use a triple equal to check not only a value but also its type.
if (Name===null || Surname===null) {
In case of falsy values simply use if (!Name || !Surname), then it checks for nulls, empty strings, false and undefined.
A single equal is assignation, if (Name==null && Name="") - sets Name to an empty string, not sure if it's a desired flow.
if Name and Surname are html input tags, then their value is of a string type and is under .value property.
In this case the code should looks like
var Name=document.getElementById("Name").value.trim(); // avoid spaces
var Surname=document.getElementById("Surname").value.trim(); // avoid spaces
if (Name==="" || Surname==="")
{
alert("Enter the name or surname");
return false;
}
return true;

check if array has the user inputted value

I am using an input field to put user inputs in an array.
I want to check if the user inputted number is already in the array or not. And if it is in the array then the input should not be re-added.
Here is my attempt.
if(e.keyCode === 43){
var num = document.getElementById("numbers").value;
var oks = [];
// set num
// check if num is in the oks array
if( oks[num]==num ){
alert("It is already there.");
}
else{
oks[num.value]=num.value;
}
console.log(oks.value);
}
With the above code it says undefined in the console log.
Please help me find where I am wrong in this.
Thanks a lot :)
Your code has lots of mistakes, such as :
var oks = [];
The above is saying that every time the user inputs something, the array is empty, therefore there is nothing there, therefore the value is not there, so there is no use of trying to know whether the value exists or not, because it doesn't, so you should declare the oks variable outside of the eventListener.
oks[num]
The above is not the value, it's the element in the array whose index is the value, which are very different.
num.value
The above is a syntax error, because the num variable is a number not a dom element that has a value attribute.
And here's the solution to your problem :
if( oks.indexOf(num)>-1 ){
alert("It is already there.");
}
else{
oks.push(num);
}
you can do
if(oks.indexOf(num) != -1)
to check whether it lies in the array or not or alternatively you could use oks as an object and check if a fiels of a similar value is defined or not, which should be more efficient
var oks = [];
is being initialised on every request, hence it is always empty, initialise it at a parent/global scope, you should use
var oks = {};
// at a parent scope
if(e.keyCode === 43){
var num = document.getElementById("numbers").value;
// set num
// check if num is in the oks array
if( oks{num} != undefined ){
alert("It is already there.");
}
else{
oks[num]=true;
}
console.log(oks.num);
}

checking values before submitting form

Before I submit a form I want to check the values in the input.
Here I'm checking if a value is NOt equal to .5 or 1. or not a empty string.
form.onsubmit = function(e) {
var ftimes = document.getElementsByClassName("add_timebox");
var fflag = 0;
for(i=0;i< ftimes.length;i++) {
var value1 = ftimes[i].value;
console.log(value1);
if ( value1 !==.5 ||value1 !== 1 || (!IsStringEmpty(value1)) ){
fflag = 1;
console.log('inside');
}
}
if(fflag==1) {
alert('enter again' );
return false;
}
I have made many changes to the IF statement to try to get it correct.
But it is still going in the loop even when I know if shouldn't.
For example when i submit the form and i have one input value equal .22
then it should only give me 1 'inside' but in keeps repeating:
inside
.22
(empty string)
inside
....
You do not show how you are implementing your IsStringEmpty method, but if you are using something like this, then any number is also a non-empty string, so your if statement will always run.
function IsStringEmpty(str) {
return (!str || 0 === str.length);
}
So you need to change your ORs with ANDs, or it will never check the number conditions.
You can check if the value is not an empty string and is different from 0.5 and 1. Then your condition should be like this.
if (!IsStringEmpty(value1) && value1 !== 0.5 && value1 !== 1)
But, you are getting the value from a form, so it will be a string. Therefore, you are comparing strings and you need this.
if (!IsStringEmpty(value1) && value1 !== ".5" && value1 !== "1")
Although you will probably want to compare floats, in which case you need this.
if (!IsStringEmpty(value1) && parseFloat(value1) !== .5 && parseFloat(value1) !== 1))
So basically, when you enter 1, .5 or and empty string in all of the form fields, you skip the inside block. But if you have any other value in any of the fields, then the flag will be set to 1. If that is not what you meant, please update your question to be more specific.
Please check Plunker here.
Hope this helps.
you have to add a break; statment in your if condition once the if condition is satisfied.
if ( value1 !==.5 ||value1 !== 1 || (!IsStringEmpty(value1)) ){
fflag = 1;
console.log('inside');
break;
}

Checking textbox if it's empty in Javascript

I wrote a simple html file with a textbox and submit button, and it generates and document.write's a response dependant on what you submit. I want to have it generate a response saying to enter content if the box is empty. The textbox's id is chatinput, so I have the following the code in the beginning
var chatinput_box=document.getElementById('chatinput');
var chatinput=chatinput_box.value;
Then a have a conditional, although I can't get it to work correctly; I've tried
if(chatinput==""){}
if(chatinput.length=0){}
if(chatinput=null){}
and others but none have worked correctly. Does anyone have another idea?
It should be this:
var chatinput = document.getElementById("chatinput").value;
if (chatinput == "" || chatinput.length == 0 || chatinput == null)
{
// Invalid... Box is empty
}
Or shorthanded:
if (!document.getElementById("chatinput").value)
{
// Invalid... Box is empty
}
The = assigns a value whereas == checks whether the values are equal.
Just offering an alternative, not trying to steal thunder ...
Create an isEmpty function to reuse on a variety of items.
function isEmpty(val){
return ((val !== '') && (val !== undefined) && (val.length > 0) && (val !== null));
}
Then you can apply it to whatever element you want:
if(!isEmpty(chatinput)){
// hooray its got a value!
}
Not exactly original, its the concept stolen from PHP, but it comes in handy a lot.

How to check for empty value in Javascript?

I am working on a method of retrieving an array of hidden inputs in my form like so
<input type="hidden" value="12:34:00" name="timetemp0">
<input type="hidden" value="14:45:00" name="timetemp1">
<input type="hidden" value="15:12:00" name="timetemp2">
<input type="hidden" value="16:42:12" name="timetemp3">
<input type="hidden" value="16:54:56" name="timetemp4">
<input type="hidden" value="17:03:10" name="timetemp5">
My javascript function retrieves these individually by using getElementsByName('timetemp'+i)
for (i ; i < counter[0].value; i++)
{
//finds hidden element by using concatenation of base name plus counter
var timetemp = document.getElementsByName('timetemp'+i);
//if there is a value alert that value to user - this is just for testing purposes at the moment
//because there is only one of timetemp.i then it occupies position 0 in array
if (timetemp[0].value == null)
{
alert ('No value');
}
else
{
alert (timetemp[0].value);
}
}
So what should happen is it will alert the user of the value in that hidden input but if it comes accross an input with no value like this:
<input type="hidden" value="" name="timetemp16">
Then it will say "No value"
However th if function cannot seem to work with this:
I have tried:
(timetemp[0].value == null)
(timetemp[0].value === null)
(timetemp[0].value == undefined)
(timetemp[0].value == '')
It always seems to default to else clause.
Any ideas?
Comment as an answer:
if (timetime[0].value)
This works because any variable in JS can be evaluated as a boolean, so this will generally catch things that are empty, null, or undefined.
In my opinion, using "if(value)" to judge a value whether is an empty value is not strict, because the result of "v?true:false" is false when the value of v is 0(0 is not an empty value). You can use this function:
const isEmptyValue = (value) => {
if (value === '' || value === null || value === undefined) {
return true
} else {
return false
}
}
First, I would check what i gets initialized to, to see if the elements returned by getElementsByName are what you think they are. Maybe split the problem by trying it with a hard-coded name like timetemp0, without the concatenation. You can also run the code through a browser debugger (FireBug, Chrome Dev Tools, IE Dev Tools).
Also, for your if-condition, this should suffice:
if (!timetemp[0].value) {
// The value is empty.
}
else {
// The value is not empty.
}
The empty string in Javascript is a falsey value, so the logical negation of that will get you into the if-block.
Your script seems incorrect in several places.
Try this
var timetemp = document.getElementsByTagName('input');
for (var i = 0; i < timetemp.length; i++){
if (timetemp[i].value == ""){
alert ('No value');
}
else{
alert (timetemp[i].value);
}
}
Example: http://jsfiddle.net/jasongennaro/FSzT2/
Here's what I changed:
started by getting all the inputs via TagName. This makes an array
initialized i with a var and then looped through the timetemp array using the timetemp.length property.
used timetemp[i] to reference each input in the for statement
The counter in your for loop appears incorrect (or we're missing some code). Here's a working Fiddle.
This code:
//Where is counter[0] initialized?
for (i ; i < counter[0].value; i++)
Should be replaced with:
var timeTempCount = 5; //I'm not sure where you're getting this value so I set it.
for (var i = 0; i <= timeTempCount; i++)
const isEmptyValue = val => [null, undefined, ''].includes(val);

Categories

Resources