Dynamic if statement in JS - javascript

I have a function that looks through arrays and returns ether true or false and will change a global variable to the number that it found if it was above 0. I want to have a if statement that changes so if it is that number it'll call a different function based on that number without having multiple if statements. So something like
if(left == true){
for(i=1;i<8;i++){
if(leftnumber == i){
//function based on i
}
}
}

You can use an object to lookup a function based on the number.
// object that stores functions based on "leftnumber"
var fnTable = { };
// when "leftnumber" is 6, this function will be called
fnTable[ 6 ] = function() { ... };
// ... for loop stuff
// attempt to find the function for the value at i
var lookup = fnTable[ i ];
// if it exists, call it
if (lookup)
lookup( );

Something like this?
function myfunction(number){
//do stuff
}
if(left == true){
for(i=1;i<8;i++){
if(leftnumber == i){
myfunction(i);
}
}
}

Related

Only execute function if value is NOT empty [duplicate]

This question already has answers here:
How to check if a value is not null and not empty string in JS
(11 answers)
Closed 4 years ago.
I have the following html, which is part of a webform:
<input type="hidden" name="userID" id="control_COLUMN43" value="%%userID%%">
The value of this field is dynamically generated by a database. It's possible that the value of this field is empty.
Next to this, I created a function which sends the value of this field (via Ajax) to another database, upon a submit of the webform.
What I want to do now is: only execute this function if the value of the field "userID" is NOT empty. If it's empty, I don't want this function to be executed.
So I assume it will be something like this, but I'm struggling to find the correct way to do this:
if (#control_COLUMN43 !=== "") //this is the id of the field
{
function SendAjax()
{
if
{
//code
}
else
{
//code
}
}
}
else
{
//don't execute function
}
Or the other way around I guess?
Can anybody help me with this?
Thanks in advance!
Use like this
// Also u can add null check
if(data !== '') {
// do something
}
If, however you just want to make sure, that a code will run only for "reasonable" values, then you can, as others have stated already, write:
if (data) {
// do something
}
Since, in javascript, both null values, and empty strings, equals to false (i.e. null == false).
The difference between those 2 parts of code is that, for the first one, every value that is not specifically an empty string, will enter the if. But, on the second one, every true-ish value will enter the if: false, 0, null, undefined and empty strings, would not.
You should not declare functions inside the conditions. If you do then at the time of execution if the condition is not met, function will not be available which may lead to errors. Hence, you should place the condition inside the function.
You can modify your condition to following
function SendAjax() {
if (document.getEelementById("control_COLUMN43").value) {
//code
}
}
You can access the value of the input by using getElementById(id).value
and declare your function outside the if block like:
function SendAjax()
{
if
{
//code
}
else
{
//code
}
}
if (document.getElementById('txt_name').value) //this is the id of the field
{
SendAjax()
}
else
{
//don't execute function
}
The if statement you need, without JQuery, should be like this:
if (document.getElementById("control_COLUMN43").value !=== "") {
// .. commands
}
First get your hidden input value using document.getElementById() and then check if it is null like following:
var userId = document.getElementById("control_COLUMN43");
if (userId) //this is the id of the field
{
SendAjax()
}
else
{
alert("UserId is null);
}
function SendAjax()
{
if
{
//code
}
else
{
//code
}
}
In if condition check $("#control_COLUMN43").val()
It can be null or '' so you can apply condition accordingly.
You can check empty value like this
function isEmpty(str) {
return (!str || 0 === str.length);
}
var val = document.getElementById('control_COLUMN43').value;
var col = isEmpty(val);
if (col) {
function SendAjax(){
if
{
//code
}
else
{
//code
}
}
}
else
{
//don't execute function
}
There are several issues at once:
You are mixing up declaring a function with calling it.
To get the value from a control, use document.getElementById("...").value
The proper notation for not === is !==.
This is how it goes:
// Declare the function
function SendAjax()
{
if
{
//code
}
else
{
//code
}
}
// Get value
var value = document.getElementById("control_COLUMN43").value;
// Call the function conditionally
if (value !== "")
{
SendAjax();
}
The code you write in if condition is not correct ID value must be get like:
if(document.getElementById("control_COLUMN43").value != ''){
//Your code here
}
Basically you have to check value property of the input element. Using dom selectors first you can select a element using id then you can access value attribute for element. If it's not null or undefined or just empty spaces then you can call your function
function handleClick(){
// Extract value from input element
let val = document.getElementById('input').value;
// Check value is empty or not
if(val){
// If not empty
console.log('Value is : ' + val);
}
else{
// If empty
console.log('Empty input');
}
}
<input id="input" type="text">
<button onclick="handleClick()">SUBMIT</button>
// get the contents of the form element
var control_COLUMN43 = document.getElementById("control_COLUMN43").value;
// process the data
if( control_COLUMN43 != "" ) {......

How to check on a button click which function was last called out of many custom functions in javascript?

The first method sets the array of objects in the variable final,the second method sets the array of objects in the variable final1.In this particular save method I want to check in the else condition which method was called last(method1 or method2) so that I can decide which variable should I use inside fetchItemId function?
function save(){
if (final === undefined && final1 !== "")
fetchItemId(final1);
if (final1 === undefined && final !== "")
fetchItemId(final);
else {
// I want to call the last executed method out of 2
}
}
You can use a flag variable to check this.
Eg
var i=0;
method1()
{
//whatever
i=1;
}
method2()
{
//whatever
i=2;
}
In your else check value of i.
if(i=1)
// method1 was called last
else
if(i=2)
//method2 was called last
else if (i=0)
// none was called

If clause with multiple conditions

I seem to be lost or just seem to be confused.
To simplify the problem: I want to check whether each in an array holds true and if and only if all are true it should return a specific value.
var trueArray=[true,true,true,true];
As in my code, the array can have length up to 100 elements, I can't simply check for every element but need a for loop.
for(var i=0;i<trueArray.length;i++){
if(trueArray[i]===true)
{
//do something
}
}
However, the above code does something on each step of the loop but I only want it to do something once every condition held true and not in between. Can't think of the solution at the moment?
Use Array.prototype.every
if (trueArray.every(function(x) { return x; })) {
//do something
}
If it's guaranteed to be a boolean you can check if any of them are false instead of if they're all true with Array.prototype.indexOf
if(trueArray.indexOf(false) === -1) {
// none are false, so do stuff
}
You wouldn't need to use a loop or create a function.
Declare a check variable who is already true and set it to false if one of your array values is false. After that, check if it's true and do something.
Example:
var trueArray=[true,true,true,true];
var bCheckArrayVal = true;
for(var i=0;i<trueArray.length;i++){
if(trueArray[i]===false){
bCheckArrayVal = false;
}
if (bCheckArrayVal) {
// do something if true
} else {
// do something if false
}
}
Try the following code:
var currentValue = true;
for(var i=0;i<trueArray.length;i++){
if(trueArray[i]===false){
currentValue = false;
}
}
if(currentValue === true){
//do something
}
You should short circuit the logic as soon as you get a false value, must answers are not getting your question because of the misleading logic you put inside the for even though you only want it done once if all values are true.
You need something like
var flag=true;
for(var i =0;i
if (flag) { do something}
You can do it like this...
var trueArray=[true, true, true, true];
var allTrue=false;
for(var i=0;i<trueArray.length;i++){
if(trueArray[i]===false){
allTrue=false;
break;
}
else
{
allTrue=true;
}
}
if(allTrue==true)
{
// do something if all values are true
}
You must break the loop if the false value is detected.

How can I set the contents of an array inside an object to false if it is null?

I am using the following to get some data and load it into an object:
test.qs = data;
The object qs then looks something like this:
[
{"answer":null,
"answered":true,
// many more fields here
"answers":{"correct":null,"response":null}},
{"answer":null,
"answered":true,
// many more fields here
"answers":{"correct":null,"response":null}}
]
How can I make it so that if the response value in the array is null then it is changed to false?
var x=[
{"answer":null,
"answered":true,
// many more fields here
"answers":{"correct":null,"response":null}},
{"answer":null,
"answered":true,
// many more fields here
"answers":{"correct":null,"response":null}}
];
var string=JSON.stringify(x).toString().replace(/\:null/g, ":false");
var json=jQuery.parseJSON(string);
This will change all null's into false
Try this:
$(test.qs).each(function () {
$(this).each(function (i) {
for(var props in this) {
if(test.qs[i][props] == null)
test.qs[i][props] = false;
}
});
});
Note:
You need jQuery to perform this code + depending on where you are pasing the code, it should be available globally, so if the code doesn't work add next one where your variable is declared:
window.test = test;
As I understand it: You want to change the value of "response" to false if it has the value "null". Assuming that each object in your Array has the same structure, than this should work:
for(var i = 0; i < test.qs.length; ++i)
{
if(test.qs[i]["answers"]["response"] == null)
{
test.qs[i]["answers"]["response"] = false;
}
}

What is the best way to have a function toggle between two different processes?

I have a function that I want it execute alternating processes every time it's triggered. Any help on how I would achieve this would be great.
function onoff(){
statusOn process /*or if on*/ statusOff process
}
One interesting aspect of JavaScript is that functions are first-class objects, meaning they can have custom properties:
function onoff() {
onoff.enabled = !onoff.enabled;
if(onoff.enabled) {
alert('on');
} else {
alert('off');
}
}
For this to work, your function should have a name. If your function is anonymous (unnamed), you can try to use arguments.callee to access it, but that is deprecated in the new ES5 standard and not possible when using its strict mode.
With the use of closures, you can define a static variable that is only accessible by the function itself:
var toggle = (function()
{
var state = true;
return function()
{
if(state)
alert("A");
else
alert("B");
state = !state;
};
})();
Now you can repeatedly invoke toggle(), and it would alternate between "A" and "B". The state variable is unaccessible from the outside, so you don't pollute the global variable scope.
Use closures. In addition to closures, this method demonstrates arbitrary arguments and arbitrary numbers of functions to cycle through:
Function cycler
function cycle() {
var toCall = arguments;
var which = 0;
return function() {
var R = toCall[which].apply(this, arguments);
which = (which+1) % toCall.length; // see NOTE
return R;
}
}
Demo:
function sum(a,b) {return a+b}
function prod(a,b) {return a*b}
function pow(a,b) {return Math.pow(a,b)}
function negate(x) {return -x;}
var f = cycle(sum, prod, pow, negate);
console.log(f(2,10)); // 12
console.log(f(2,10)); // 20
console.log(f(2,10)); // 1024
console.log(f(2)); // -2
// repeat!
console.log(f(2,10)); // 12
console.log(f(2,10)); // 20
console.log(f(2,10)); // 1024
console.log(f(2)); // -2
Arbitrary cycler
Alternatively if you do not wish to assume all cycled things are functions, you can use this pattern. In some ways it is more elegant; in some ways it is less elegant.
function cycle() {
var list = arguments;
var which = 0;
return function() {
var R = list[which];
which = (which+1) % toCall.length; // see NOTE
return R;
}
}
Demo:
var cycler = cycle(function(x){return x}, 4, function(a,b){return a+b});
cycler()(1); // 1
cycler(); // 4
cycler()(1,5); // 6
// repeat!
cycler()(1); // 1
cycler(); // 4
cycler()(1,5); // 6
NOTE: Because javascript thinks 10000000000000001%2 is 0 (i.e. that this number is even), this function must be three codelines longer than necessary, or else you will only be able to call this function 10 quadrillion times before it gives an incorrect answer. You are unlikely to reach this limit in a single browsing session... but who knows
If I'm understanding what you want, this may be what you're looking for:
var AlternateFunctions = function() {
var one = function() {
// do stuff...
current = two;
}, two = function() {
// do stuff...
current = one;
}, current = one;
return function() {
current();
}
}();
Then calling AlternateFunctions(); will cycle between one() and two()
There are a couple of good answers already posted, but I'm wondering what you're trying to achieve. If you're keeping track of some DOM element's state, instead of having state saved within the function, you should check the state of the element so that the function isn't operating in a vacuum (and possibly not doing what you expect). You can check some attribute, e.g., class:
function onoff(obj){
if(obj.className === 'on') {
obj.className = 'off';
}else{
obj.className = 'on';
}
}
var last=0;
function toggle() {
if(last) {
last=0;
// do process 2
}
else {
last=1;
// do process 1
}
}
See jsfiddle demo
var status=true;
function onOff(el){
/*
* toggle
*/
status = (status ? false : true);
status
? el.html('on')
: el.html('off');
}

Categories

Resources