0
<script type="text/javascript">
$(document).ready(function() {

        var sub_total = $("sub_total").text();
                        alert(sub_total);
        var ship_total = $("ship_total").val()
                        alert(ship_total);

        var new_total = sub_total + ship_total;

        $('#new_total').html( new_total.toFixed(2));
    });

</script>

I'm using alert to test the output and It is not getting the value inside the span ID.

$<span id="sub_total"><?php echo $sub_total = number_format($this->cart->total(), 2); ?></span></td>

This does display correctly on the page but the alert is a blank box. Causing the new_total value to stat NaN not a number.

How do I add the values in these two fields?

4

2 回答 2

1

EDIT:

You forgot to get the value - you are only getting the element

Since you're already using jQuery you can get the value like

var sub_total = parseInt($("#sub_total").text());// this is where you need to use .text()
var ship_total = parseInt($("#ship_total").text());

or if you want to keep plain js..

document.getElementById("sub_total").value

Since you have $ in your text you need to get rid of it before parsing it. You can use regex as @Bubbles stated or whatever method you want to remove the $ sign.. ex. substring.. split..

$.trim($("#sub_total").text().split('$')[1])

or

$.trim($("#sub_total").text()).substring(1)
于 2012-10-07T19:21:26.013 回答
0

wirey gives a good review of part of the problem, but as is I don't believe it's enough. "parseInt" won't work on "$20", you have to remove the dollar sign first. If you're feeling lazy, this is nothing a good regex won't be able to solve in short order:

var sub_total = parseInt($("#sub_total").text().match(/[0-9]+/)));
var ship_total = parseInt($("#ship_total").text().match(/[0-9]+/)));

This will just grab the number from the span, then parse it.

于 2012-10-07T19:27:18.260 回答