问题描述:

I am trying to add/subtract from a number inside a span tag. This is depenent on a checkbox. Here is the jquery I'm trying:

//If checked

var $newprice = $("#totalprice").val() + 299;

$("#totalprice").text($newprice);

//If NOT checked

var $newprice = $("#totalprice").val() - 299;

$("#totalprice").text($newprice);

If I check the box, it adds 299, but unchecked changes the number to -299.

网友答案:

For span you need to use text() method to get content not val(). In both case val() returns an empty string. In first case just string concatenation will be happen. In second case it will be "" - 231 which results -231, where the empty string act as 0.

So you can use text() with callback which hold index and old value, parse the old value and add or subtract value and return it for update.

//If checked
var $newprice = $("#totalprice").text(function(i,v){
    return parseInt(v,10) + 299;               
});
//If NOT checked
var $newprice = $("#totalprice").text(function(i,v){
    return parseInt(v,10) - 299;               
});
网友答案:

You have to do this in change event of your checkbox:

$(':checkbox').change(function() {
  if (this.checked) {
    //If checked
    var $newprice = +$("#totalprice").text() + 299;
    $("#totalprice").text($newprice);
  } else {
    //If NOT checked
    var $newprice = +$("#totalprice").text() - 299;
    $("#totalprice").text($newprice);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  <input type='checkbox'>
  <span id='totalprice'>0</span>
</p>
相关阅读:
Top