...

View Full Version : Adding values of array to IF condition



darrylm
10-30-2012, 01:18 PM
I am attempting to create a function that follows similar logic to the following:


function ___ (array1, array2) {
if( for (i in array1) {
$("#"+array1[i]).val() != ""}){
for (i in array2) {
$("#"+array1[i]).show()}
}
}

I want to feed an array of values into a function, every value in the array must act as an extra condition in an IF statement.
Is it possible?

My best attempt was the next chunk of code which fell flat.
I attempted to create a string representing the condition, but the IF treats the var as the condition( therefore testing its existence), not the value it represents.



$(document).ready(function(e) {
var q = ['fname', 'lname'];

_____(q, "");
});

function _____(q, a){

// Initialize the condition
var condition = "";
// Create a count for conditions
var count = 0;
// Loop through array containing IDs to be included in the condition
for ( i in q ) {
// If the condition is not the first, add &&
if(count == 0) {
condition += '$("#' + q[i] + '").val() != "" ';
} else {
condition += '&& $("#' + q[i] + '").val() != ""';
}
// Increment count
count++;
}
}


I apologise if the above isnt as clear as it should be.

*There is jQuery included in that code

devnull69
10-30-2012, 03:02 PM
Maybe like this?



function multipleCondition(myArray, myValue) {
var returnValue = true;
for(i=0; i<myArray.length; i++) {
if(myArray[i] == myValue) returnValue = false;
}
return returnValue;
}

// example
if(multipleCondition(["fname", "lname"], "")) {
// all of the array conditions are true
}

The function will return "true" only if all of the array elements are != to the myValue parameter. If one of the elements is equal to myValue, it will return false and the whole multiple condition fails.

Dormilich
10-31-2012, 09:11 AM
isn’t that the same as

if (-1 === myArray.indexOf(myValue)) {
// myValue not in myArray
}
?

devnull69
10-31-2012, 10:29 AM
Yes you are right ... I forgot to include the jQuery part


function multipleCondition(myArray, myValue) {
var returnValue = true;
for(i=0; i<myArray.length; i++) {
if($('#'+myArray[i]).val() == myValue) returnValue = false;
}
return returnValue;
}

// example
if(multipleCondition(["fname", "lname"], "")) {
// all of the array conditions are true
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum