密钥:选中复选框时添加值

时间:2014-11-29 09:40:34

标签: javascript jquery checkbox keyup

所以我使用Keyup来计算输入字段的总数。到现在为止还挺好。 但现在我想这样做: 如果选中复选框#a,则将总数加12。如果没有,请添加0。

我的代码基于:http://jsfiddle.net/5xzSy/1/

$(document).keyup(function(){ // run anytime the value changes
  var element1 = parseFloat($('#element1').val())  * 16.28 || 0; // get value of field and multiply by price
  var total = 0+element1
});

如果人们取消选中它,我如何添加已选中复选框的值并将其减去。 (或甚至更好:使用radiobutton?) 谢谢!

2 个答案:

答案 0 :(得分:1)

演示:http://jsfiddle.net/5xzSy/1079/ < - 已更新(仅在给出内容时添加12,浮动数字)

btw:input<input/>而不是<input></input>

$('input').keyup(function(){ // run anytime the value changes        
  var firstValue = parseFloat($('#first').val()); // get value of field
  var secondValue = parseFloat($('#second').val()); // convert it to a float
  var thirdValue = parseFloat($('#third').val());    
  $('#added').html(firstValue + secondValue + thirdValue); // add them and output it
});

$('#check').on('change', function () {
  var total = parseFloat($('#added').text()); // <-- update for float
  if (total) {
      if ($(this).is(':checked')) {
          total = total + 12;
      } else {
          total = total - 12;
      }
      $('#added').text(total);
  }
})

答案 1 :(得分:0)

应该这样做......

$(document).keyup(function(){ // run anytime the value changes
  var element1 = parseFloat($('#element1').val())  * 16.28 || 0; // get value of field and multiply by price
  var total = element1;
  if ($('#a').is(':checked')) {
    total = total + 12;
  }
});
相关问题