需要添加不与 USD 连接

Need to add not concatenate with USD

我知道有人问过这个问题,但每种情况都各不相同,足以让我感到困惑。

当用户更改 select 时:#cost + #donation = #total

当用户输入#donation 时:#cost + #donation = #total

我有它的工作,但总数连接到“$30.00$20.00”而不是将 2 添加到“$50.00”

我相信 parseFloat() 与它有很大关系。

谢谢!

<select class="custom-select d-block w-100" id="type" name="type" required>

<input type="text" class="form-control" id="cost" name="cost" disabled>

<input type="text" class="form-control" id="donation" name="donation">

<input type="text" class="form-control" id="total" name="total" disabled>

这是我拼凑的:

    $("#type").change(function(){
    // this changes the input id=cost to match the select field id=type
    var typevalue = $( "#type" ).val();
    $('input[name=cost]').val(typevalue);


});

 $('#donation').keyup(function() {

   $(this).val(function(i,v) {
     return '$' + v.replace('$',''); //remove exisiting, add back.
   });

 });

$(document).ready(function(){
    $('#type').change(calculate);
    $('#donation').keyup(calculate);

});

function calculate(e)
{
    $('#total').val($('#cost').val() + $('#donation').val());
} 

尝试在添加之前从数字中删除美元符号:String.replace("$",""),然后使用 parseFloat(value)

解析它

您可以将输入字段包裹在 <label> 中并在其中添加 $ 符号。

我也会使用 <input type='number'> 让您的客户更轻松。

同时将成本选择器更改为 $('#cost')

将值转换为整数或浮点数以确保您使用的是数字:

function calculate(e)
{
    var cost = parseInt($('#cost').val().replace('$',''));
    var donation = parseInt($('#donation').val().replace('$',''));
    var total = cost + donation;
    $('#total').val('$'+ total );
}