The following Javascript is attached to a field form (on change ) it is supposed to ensure that if the user clicks on a button then 'off site' will populate in activity_type. And if not then '95 Modifier' will appear. In addition this form sheet has a field I have checked 'required' yet what is happening is the user is able to enter blanks for activity type. Is there a way within this javascript to then not allow a blank to be entered?
if (getFormElement('activity_type_id').toUpperCase()=='EE641670-8BE3-49FD-8914-030740D9DE72'
&& getFormElement('actual_location').toUpperCase()!='5E74C25C-6363-46BE-B030-16216B364F5A')
{
setFormElement('is_off_site',true);
} else
{
setFormElement('is_off_site',false);
}
{
setFormElement('is_off_site',false);
}
For your requirement custom function might solve your issue. It might cover almost your all primary scenarios. I have tried my best to update an answer with the best possibilities.
Please review it.
function isEmpty(inputValue) {
if(typeof inputValue === 'string' && (inputValue === '0' || inputValue === 'false' || inputValue === '[]' || inputValue === '{}' || inputValue === '')){
return true;
}else if(Array.isArray(inputValue) === true){
return inputValue.length === 0 ? true : false;
}else if(Array.isArray(inputValue) === false && (typeof inputValue === 'object' && inputValue !== null) && typeof inputValue !== 'undefined' && typeof inputValue !== null){
return Object.keys(inputValue).length === 0 ? true : false;
}else if(typeof inputValue === 'undefined'){
return true;
}else if(inputValue === null){
return true;
}else if(typeof inputValue === 'number' && inputValue === 0){
return true;
}else if(inputValue === false){
return true;
}else if(inputValue.length > 0 && inputValue.trim().length === 0){
return true;
}
return false;
}
console.log("isEmpty(' '): ",isEmpty(' '));
console.log("isEmpty(''): ",isEmpty(''));
console.log("isEmpty([]): ",isEmpty([]));
console.log("isEmpty({}): ",isEmpty({}));
console.log("isEmpty(): ",isEmpty());
const nullValue = null;
console.log("isEmpty(null): ",isEmpty(nullValue));
console.log("isEmpty(0): ",isEmpty(0));
console.log("isEmpty(false): ",isEmpty(false));
console.log("isEmpty('0'): ",isEmpty('0'));
console.log("isEmpty('false'): ",isEmpty('false'));
console.log("isEmpty('[]'): ",isEmpty('[]'));
console.log("isEmpty('{}') ",isEmpty('{}'));
console.log("isEmpty(''): ",isEmpty(''));
console.log("isEmpty('0.0'): ",isEmpty(0.0));
i have this error in internet explorer console ' Object doesn't support property or method 'isInteger' ' how can i resolve it ?
code:
function verificaNota(nota){
if (nota.length>0){
var arr = [];
if( nota.indexOf(".") != -1 ){
return ferificareArrayNote(nota.split('.'));
}else if( nota.indexOf(",") != -1 ){
ferificareArrayNote(nota.split(','));
}else if( nota.length<=2 && Number.isInteger(Number(nota)) && Number(nota)<=10 && Number(nota) > 0){
return true;
}else {
return false;
}
}
return true;
}
And yes, i pass it a number not char;
As stated by #Andreas, Number.isNumber is part of ES6 so not supported by IE11
You can add the following polyfill to you javasript
Number.isInteger = Number.isInteger || function(value) {
return typeof value === "number" &&
isFinite(value) &&
Math.floor(value) === value;
};
source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
this is a very dummy question for all the experts here I suppose.
I have a bunch of if statements (16), and I'm trying to find a way to write 48 lines of code in much less because I'm sure it's possible.
I've read everywhere that long if/else if statements are bad practices.
So how to write this bunch of code the clever way? Thanks
if (!latitude || typeof latitude == 'undefined') {
latitude == 'undefined';
} else if( !longitude || typeof longitude == 'undefined' ) {
longitude == 'undefined';
} else if( !name || typeof name == 'undefined' ) {
name == 'undefined';
} else if( !adresseNum || typeof adresseNum == 'undefined' ) {
adresseNum == 'undefined';
} else if( !adresseVille || typeof adresseVille == 'undefined' ) {
adresseVille == 'undefined';
} else if( !adresseDpt || typeof adresseDpt == 'undefined' ) {
adresseDpt == 'undefined';
} else if( !adresseRg || typeof adresseRg == 'undefined' ) {
adresseRg == 'undefined';
} else if( !adresseFr || typeof adresseFr == 'undefined' ) {
adresseFr == 'undefined';
} else if( !adresseCp || typeof adresseCp == 'undefined' ) {
adresseCp == 'undefined';
} else if( !telephone || typeof telephone == 'undefined' ) {
telephone == 'undefined';
} else if( !horaires || typeof horaires == 'undefined' ) {
horaires == 'undefined';
} else if( !note || typeof note == 'undefined' ) {
note == 'undefined';
} else if( !reviewFinale || typeof reviewFinale == 'undefined' ) {
reviewFinale == 'undefined';
} else if( !website || typeof website == 'undefined' ) {
website == 'undefined';
} else if( !types || typeof types == 'undefined' ) {
types == 'undefined';
} else {
console.log('All fields OK');
}
var isOk = [
latitude,
longtitude,
name,
adresseNum,
adresseVille,
adresseDpt,
adresseRg,
adresseFr,
adresseCp,
telephone,
horaires,
note,
reviewFinale,
website,
types
].every(function (value) {
return !!value;
});
if (isOk) {
console.log('All fields OK');
}
But I think you'd better combine all variables to object or form
you can do a function that checks them all like this
var isDefined = [latitude, longtitude, name, adresseNum, adresseVille, adresseDpt, adresseRg, adresseFr, adresseCp, telephone, horaires, note, reviewFinale, website, types].every(function (value) {return !!value;});
With ES6, you could use an object with all variables as key and value pair, then iterate with Array#every and assign on falsy values undefined and check the result with an if statement.
var data = { latitude, longitude, name, adresseNum, adresseVille, adresseDpt, adresseRg, adresseFr, adresseCp, telephone, horaires, note, reviewFinale, website, types };
if (Object.keys(data).every(k => data[k] || (data[k] = 'undefined', false))) {
console.log('All fields OK');
}
is every variable defined by itself or is it coming from another object or similar to var telephone = obj.telephone?
if that is the case you could do something like this:
var ok = true;
for (var o in obj) {
if (!obj[o]) {
obj[o] == 'undefined';
ok = false;
}
}
if (ok) {
console.log('all fields are ok');
}
An option that might works is using default value in argument destructure. Basically you check for every variable if it's undefined (by the way, what happens if one of those are the value 'false'?).
This is specific for this case though...
function functionWithSomeLogic({
latitude = 'undefined',
longitude = 'undefined',
name = 'undefined',
adresseNum = 'undefined'
// ... and the rest of the variables
}) {
// Do whatever here, all the arguments are initialized or have the string value of 'undefined'
}
by the way, if instead of setting a default value you would like to throw an exception
const throwArg = argName => throw new Error(`Argument missing: ${argName}`);
function functionWithSomeLogic({
latitude = throwArg('latitude'),
longitude = throwArg('longitude'),
name = throwArg('name'),
adresseNum = throwArg('adresseNum')
// ... and the rest of the variables
}) {
// Do whatever here, all the arguments are initialized, if one of them
// had been undefined, an appropriate exception will be thrown before this body
}
A simple es6 function will do the trick. as #Andrey pointed out.
const areDefined = (...args) => args.every(elm => !!elm);
if(areDefined(latitude, longitude, name/*, ...*/)) {
console.log('All fields OK');
}
I have two properties where i need to check null and undefined both for each, how can i use that in if else statements ?
main.js
var validateControlRating = function () {
if ( ($scope.controlProcessRatingDTO.controlPerformanceRatingKey === null ||
$scope.controlProcessRatingDTO.controlPerformanceRatingKey === undefined)
&&
($scope.controlProcessRatingDTO.controlDesignRatingKey === null ||
$scope.controlProcessRatingDTO.controlDesignRatingKey === undefined) ) {
$scope.caculatedRatingDiv = false;
} else {
$http.get('app/control/rest/calculateControlEffectiveness/' + $scope.controlProcessRatingDTO.controlDesignRatingKey + '/' + $scope.controlProcessRatingDTO.controlPerformanceRatingKey).success(function (data) {
$scope.calcaulatedRating = data;
}, function (error) {
$scope.statusClass ='status invalid userErrorInfo';
var errorMessage = error.data.errorMsg;
if (error.data.techErrorMsg) {
errorMessage = error.data.techErrorMsg;
}
$scope.statusInfo = errorMessage;
});
$scope.ratingValidationMsg = '';
$scope.ratingWinValidationClass = 'valid';
$scope.caculatedRatingDiv = true;
$scope.enableRatingSave = false;
}
};
It's a little tedious in javascript, you have to write each condition, and use parentheses etc
if ( ($scope.controlProcessRatingDTO.controlPerformanceRatingKey === null ||
$scope.controlProcessRatingDTO.controlPerformanceRatingKey === undefined)
&&
($scope.controlProcessRatingDTO.controlDesignRatingKey === null ||
$scope.controlProcessRatingDTO.controlDesignRatingKey === undefined) ) {...
or just
if ([null, undefined].indexOf( $scope.controlProcessRatingDTO.controlPerformanceRatingKey ) === -1
&&
[null, undefined].indexOf( $scope.controlProcessRatingDTO.controlDesignRatingKey ) === -1) {...
I think you need to to check this correclty, check for undefined then for null
and use && not || because your code will go to check null value for undefined variable and this surely will throw exception
code:
if( typeof myVar == 'undefined' ? false: myVar )
{ // go here defined and value not null
}
or
code:
if(typeof myVar != 'undefined' && myVar)
{ // go here defined and value not null
}
In your code check will go like
if ((typeof $scope.controlProcessRatingDTO.controlDesignRatingKey !== undefined||
typeof $scope.controlProcessRatingDTO.controlPerformanceRatingKey !== undefined) &&
($scope.controlProcessRatingDTO.controlDesignRatingKey !== null ||
$scope.controlProcessRatingDTO.controlPerformanceRatingKey !== null)) {
// do home work
}else { // do other home work }
You can use negate operator as well, but this would make work for "false" as well:
if (!$scope.controlProcessRatingDTO.controlPerformanceRatingKey && !$scope.controlProcessRatingDTO.controlDesignRatingKey) {
This is a bit shorter but if you want to treat False values separately, then use the Adeneo's answer above.
You could do this:
if ( some_variable == null ){
// some_variable is either null or undefined
}
taken from: How to check for an undefined or null variable in JavaScript?
function validate()
{
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if ( username==null || username=="" && password==null || password=="");
{
alert("Please enter username and password");
return false;
}
else ( username == "james1" && password == "j1j22j3j" )
{
alert ("Login successfully");
window.location = "http://www.dtrekrun.com/training.html"; // Redirecting to other page.
return false;
}
}
I'm trying to validate the username/password and show an alert. But it is not working for me.
Didn't you see any error in the console?
Remove the semicolon at the end of this line:
if ( username==null || username=="" && password==null || password=="");
Else don't take arguments, else if does ! Replace
else ( username == "james1" && password == "j1j22j3j" )
by
else if ( username == "james1" && password == "j1j22j3j" )
use this
if ( username==null || username=="" && password==null || password=="")
instead of
if ( username==null || username=="" && password==null || password=="");
and
else ( username == "james1" && password == "j1j22j3j" )
by
else if ( username == "james1" && password == "j1j22j3j" )
Hope you got success
Just remove semicolon after if ( username==null || username=="" && password==null || password=="");