【问题标题】:Jquery - Adding Input value and another number together if checkbox is checkedJquery - 如果选中复选框,则将输入值和另一个数字一起添加
【发布时间】:2014-04-04 20:17:16
【问题描述】:

我正在创建一个表单,我希望用户在其中填写金额,然后显示在表单底部。然后,如果选中了一个复选框,它会将 21 添加到输入字段中的值到目前为止我有这个,但它不太工作。

http://jsfiddle.net/vePbV/

<label>Desired amount</label> <input name="tbDesiredAmount" type="number" id="tbDesiredAmount" min="50" />
<label>Include Apron?</label> <input id="cb_Apron" type="checkbox" name="cb_Apron" /> 

<p>Total: £<span id="total">0</span>.00</p>



$('#tbDesiredAmount').blur(function() {
        var value = $('#tbDesiredAmount').val();
        $("#total").empty().append(value);
});
$('#cb_Apron').blur(function() {
        var value = $('#tbDesiredAmount').val();
        var apron = 21;
        var total = value + apron; 
        $("#total").empty().append(total);
});

所以和我想要它做的例子。

  • 在“所需金额”中键入 70,当您离开输入字段时,在 #total 中显示 70。
  • 检查围裙复选框,将 21 添加到所需数量,以便在 #total 中显示 91
  • 如果取消选中围裙复选框,它将从#total 中的图中删除 21
  • 如果我更改所需的金额,它将更新#total,这需要与选中的复选框和未选中的复选框一起使用。

任何帮助将不胜感激,因为我现在陷入困境。

【问题讨论】:

  • 使用parseInt() - var total = parseInt(value) + parseInt(apron);
  • 金额也可以是小数。如果是这样,请使用parseFloat()
  • Krish R - 干杯,这就是将两个数字相加的结果。

标签: javascript jquery math checkbox input


【解决方案1】:

试试这个使用parseInt()

var apron = 21;
$('#tbDesiredAmount').keyup(function () {
    var value = $('#tbDesiredAmount').val();
    if ($('#cb_Apron').is(':checked')) {
        var total = parseInt(value) + parseInt(apron);
        $("#total").empty().append(total);
    } else {
        $("#total").empty().append(value);
    }
});
$('#cb_Apron').click(function () {
    if ($(this).is(':checked')) {
        var value = $('#tbDesiredAmount').val();
        var total = parseInt(value) + parseInt(apron);
        $("#total").empty().append(total);
    } else {
        var tot = parseInt($("#total").text()) - (parseInt(apron))
        $("#total").empty().append(tot);
    }
});

DEMO

【讨论】:

  • 如果我在金额中输入 70,则总计值为 70。当我选中围裙复选框时,总计值为 91。当我取消选中围裙复选框时,总计值保持 91?
  • 我将如何做到这一点,所以如果我在选中复选框后更改了所需的金额,它仍然会计算围裙价格。
  • @JordanSayner 很高兴为您提供帮助:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
  • 2022-11-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多