0

我想做的是根据选择的选项更新总价。初始价格金额来自会话变量。我已经将变量传递给 Javascript,但在使用表单时我似乎无法从该数字中添加/减去。

我错过了什么?

谢谢您的帮助。

    <script>
    $(document).ready(function()
    {   

var phonePrice = "<?php echo $q2; ?>";
var total = phonePrice;

function calcTotal()
{
    $("input:checked").each(function()
    {
        //This happens for each checked input field
        var value = $(this).attr("value");
        total += parseInt(value); 
    });
}

//This happens when the page loads
calcTotal();    
$("form").before('<p class="total">Total: <strong>' + total + '</strong></p>');
$(":submit").before('<p class="total">Total: <strong>' + total + '</strong></p>');

$("input:checkbox, input:radio").click(function()
{
    total = phonePrice;
    calcTotal();
    $("p.total").html("Total: <strong>" + total + "</strong>");
});
    });
    </script>

表格看起来像这样

    <form action="" method="post">
<fieldset id="delivery_speed">
    <legend>Options
    </legend><ol>
        <li>
            <input type="radio" name="speed" id="speed_1day" value="49" />
            <label for="speed_1day">Option 1 ($49)</label>
        </li>
        <li>
            <input type="radio" name="speed" id="speed_3days" value="0" checked />
            <label for="speed_3days">Option 2 (no charge)</label>
        </li>
        <li>
            <input type="radio" name="speed" id="speed_5days" value="-39" />
            <label for="speed_5days">Option 3 (-$39)</label>
        </li>
    </ol>
</fieldset> 
<fieldset id="browser_support">
    <legend>Additional Choices</legend>
    <p>
        <input type="checkbox" name="browser" id="browser" value="100" />
        <label for="browser">Checkbox 1 ($100)</label>
    </p>
</fieldset>
<p><input id="submit" type="submit" value="Continue to Checkout &gt;&gt;"></p>
    </form>
4

3 回答 3

2
var phonePrice = "<?php echo $q2; ?>";

假设 php 代码在渲染时会吐出这样的内容:

var phonePrice = "99.99";

引号使其成为字符串而不是数字。删除引号,您将获得一个可以正确添加的数字。

var phonePrice = <?php echo $q2; ?>;
于 2012-05-12T23:19:57.767 回答
1

删除引号phonePrice

var phonePrice = <?php echo $q2; ?>;
于 2012-05-12T23:22:33.817 回答
0

当你这样做时,问题就来了total += parseInt(value)。既然你定义phonePrice

var phonePrice = "<?php echo $q2; ?>";

它进行字符串连接但不求和。

您应该取消引用该值

var phonePrice = <?php echo $q2; ?>;

或添加另一个类型转换:

var phonePrice = parseInt("<?php echo $q2; ?>", 10);
于 2012-05-12T23:22:15.270 回答