I've got a HTML5 form with 2 dropdown inputs. The form is used to determine the distance between 2 company locations.
The current script works, but its not really good, because this would work for a few locations, but not for 23 locations as it is in my case.
How can I make an "cross reference function" that just checks a long list of vars and values?
Script:
The javascript function to check the chosen dropdown options and return the value:
inputField
is the field that shows the distance to the user.
function initCalc(inputField,select1,select2) {
select1.change(function(){
inputField.val(calculateValue(select1.val(),select2.val()));
});
select2.change(function(){
inputField.val(calculateValue(select1.val(),select2.val()));
});
}
"Calculating" the distance:
function calculateValue(firstOp,secondOp) {
var kmCost = 0.19;
if (firstOp == "Company1" && secondOp == "Company1") { var total = 0; }
else if (firstOp == "Company1" && secondOp == "Company2") { var total = 205; }
else if (firstOp == "Company1" && secondOp == "Company3") { var total = 174; }
else if (firstOp == "Company1" && secondOp == "Company4") { var total = 3; }
else if (firstOp == "Company1" && secondOp == "Company5") { var total = 21; }
else if (firstOp == "Company1" && secondOp == "Company6") { var total = 129; }
else if (firstOp == "Company2" && secondOp == "Company1") { var total = 205; }
else if (firstOp == "Company2" && secondOp == "Company2") { var total = 0; }
else if (firstOp == "Company2" && secondOp == "Company3") { var total = 11; }
//etc...
else { var total = 0; }
var total = total * kmCost;
return total.toFixed(2);
}
EDIT
With help of @JRK I came with the following, but I think I'm doing something wrong to get the value of the dropdown list from the object?
function calculateValue(firstOp,secondOp) {
var kmCost = 0.19;
var myObject = {Amsterdam : {distances : {Paris : 1, NewYork : 2}},
Paris : {distances : {Amsterdam : 1, NewYork : 3}},
NewYork : {distances : {Amsterdam : 2, Paris : 3}}
};
var total = myObject.firstOp.distances.secondOp;
var total = total * kmCost;
return total.toFixed(2);
}
EDIT2
I've got it! Thanks to this post.
function calculateValue(firstOp,secondOp) {
var kmCost = 0.19;
var myObject = {Amsterdam : {distances : {Paris : 1, NewYork : 2}},
Paris : {distances : {Amsterdam : 1, NewYork : 3}},
NewYork : {distances : {Amsterdam : 2, Paris : 3}}
};
var total = myObject[firstOp]['distances'][secondOp];
var total = total * kmCost;
return total.toFixed(2);
}