I have the following (simplified) php function which calculates a total value for me. it basically fetch an array of items from the wordpress database and checks the type of each item and then compare its value to a specific given value and sums all the comparisons up.
function total(){
$value1 = 10; // compare value for type 1 items
$value1 = 20; // type 2 items
$value1 = 30; // type 3 items
$total = 0; // reset total variable
global $wpdb;
$items = $wpdb->get_results("SELECT `item_type` as type, `item_value` as value FROM `table`"); // get all the items from database
foreach ($items as $item) {
// check which item type
switch ($item->type) {
case 1:
$total = $total + min($value1, $item->value);
break;
case 2:
$total = $total + min($value2, $item->value);
break;
case 3:
$total = $total + min($value3, $item->value);
break;
}}
return $total;
}
Now i want to remake the same function in javascript so i can use it in a form for calculations. This is what i got so far;
<SCRIPT type="text/javascript">
function calculate_total (){
var items = <?php echo json_encode($items); ?>;
var value1 = document.form.range1Input.value;
var value2 = document.form.range2Input.value;
var value3 = document.form.range3Input.value;
for each (var item in items){
switch (**(refer to item type in array)**) {
case 1:
total = total + min(value1, **(refer to item value in array)**);
break;
case 2:
total = total + min(value2, **(refer to item value in array)**);
break;
case 3:
total = total + min(value3, **(refer to item value in array)**);
break;
}}
document.form.total.value = total;
}
</script>
How can i refer to the values in the items array? I hope somebody can give me some advice on this one.
Also i saw that echo json_encode($items) formats the array as {"type":"3","value":"1.00"},{"type":"1","value":"20.50"} etc etc, I was wondering if this is a usable format for javascript because when i try total = items[1]; I see [Object Object] in the form.
$items = $pdb->get_results() is btw formatted as Array ( [0] => stdClass Object ( [type] => 1 [value] => 35.00 ) [1] => stdClass Object ( [type] => 3 [value] => 1.00 )
itemscontain.. is it json? an array? can you put that up too ? thanks :)total = items[1].valueinstead oftotal = items[1];