1

I'm making a site for myself, and I'm trying to implement some javascript for instant calculations, but I'm having some issues:

  1. Is there any way I can avoid typing

    level_prices["3"]=3;
    level_prices["4"]=4;
    

    ... etc. up to 90: in other words, is there any way I can do like I did in the PHP code and make it create this value until 90, which looks a lot cleaner?

  2. Why is this returning $Undefined? I suspect that it's not getting the value from the HTML form, but the code looks correct ...

Here is my code:

relevant HTML/PHP:

 <form action="" id="priceCalcForm" onsubmit="return false;">
  <table class="table">
   <tbody>

     <tr> <!-- first row, with css -->

        <td style="width:50%;">
            <select name="fromlevel" id="fromlevel" onchange="calculateTotal()" style="width:100%; text-align:center; font-weight:bold;">
                <option value="none" name="none">0</option>

                <?php 
                $i = 1;

                while ($i < 91) {
                    echo '
                    <option value=' . $i . ' name=' . $i . '>' . $i . '</option>';
                    $i++;
                }
                ?>  
            </select>
        </td>
       </tr>
   </tbody>
  </table>
 </form>

Included JS:

var level_prices= new Array();
level_prices["None"]=0;
level_prices["1"]=1;
level_prices["2"]=2;

function getLevelPrice()
{
    var levelSetPrice=0;
    //Get a reference to the form id="cakeform"
    var theForm = document.forms["priceCalcForm"];
    //Get a reference to the select id="filling"
    var selectedLevel = theForm.elements["fromlevel"];

    //set cakeFilling Price equal to value user chose
    //For example filling_prices["Lemon".value] would be equal to 5
    levelSetPrice = level_prices[selectedLevel.value];

    //finally we return cakeFillingPrice
    return levelSetPrice;
}

function calculateTotal()
{
//Here we get the total price by calling our function
//Each function returns a number so by calling them we add the values they return     together
    var LevelPrice = getLevelPrice();

    var divobj = document.getElementById('totalPrice');
    divobj.style.display='block';
    divobj.innerHTML = "Total Price For the Leveling $"+LevelPrice;

}

function hideTotal()
{
    var divobj = document.getElementById('totalPrice');
    divobj.style.display='none';
}

I consider myself decent with PHP, but its first time I am using JS.

4

2 回答 2

0

1)使用循环:

var level_prices = {}; // object literal not array!
level_prices['none'] = 0;
for(var i = 1; i <= 90; i++ ) {
   level_prices[i] = i;
}

第一行也可以这样写(已经定义了非属性):

var level_prices = {'none': 0};

2)level_prices 不是一个数组,它是一个对象文字(请参阅我的答案的第 1 部分)

在这里看到一个工作小提琴:http: //jsfiddle.net/BkGxq/

(另请注意,我从您的标记中删除了内联 onchange 处理程序并将其放入 javascript(在底部)

于 2013-02-23T19:40:34.617 回答
0

是的。PHP 中的任何变量(资源类型变量除外)都可以使用json_encode.

于 2013-02-23T19:42:12.037 回答