hi there this is a total noob question, so hope someone can help!
i basically want to return a cost based on a formula.
i will paste the code below and you can tell me where I am going wrong. bear in mind, this is my first stab at javascript!!
formula idea is to get the option value from a drop-down list and based on its value return a number. for example if the value is "a" return '2'. for the sake of the formula call this var vechicleTypeCost.
i have worked out how to get the distance and the rate.
The purpose of the value attribute of the option tag is to provide an internal value that the webpage will use and that the user won't see. All the user will see is what's between <option>...</option>. So, why would you use value="a" when you really want value="2"?
In any case, it's something like this:
Code:
var vehicleTypeCost;
var optionElem = document.getElementById('optionElementId');
switch(optionElem.options[optionElem.selectedIndex].value) {
case "a":
vehicleTypeCost = 2;
break;
case "b":
vehicleTypeCost = 3;
break;
default:
vehicleTypeCost = 4;
}
cost = (distance*rate)+vehicleTypeCost;
I would do something like this where you send the selected value in the <select> directly to the function that calculates the cost.
PHP Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
<!--
function calCost(vehicleTypeCost) {
if(vehicleTypeCost != 0) {
//variables distance and rate need to be defined locally or globally before this line
var cost = (distance*rate)+vehicleTypeCost;
}
}
//-->
</script>
</head>
<body>
<select id="selCost" onchange="calCost(this.options[this.selectedIndex].value)";>
<option value="0"> Select a Vehicle Type Cost</option>
<option value="2"> Vehicle Type Cost 2</option>
<option value="3"> Vehicle Type Cost 3</option>
<option value="4"> Vehicle Type Cost 4</option>
</select>
If the SELECT element is not a "multiple" one, the SELECT element takes automatically the value of the selected option as his own value. Thus, it is enough to:
Bookmarks