需要添加不与USD连接

时间:2018-05-27 10:52:34

标签: jquery concatenation add

我知道这个问题已被提出,但每个场景都变得足够混乱,以至于让我迷惑。

当用户更改选择时:#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());
} 

3 个答案:

答案 0 :(得分:0)

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

解析它

答案 1 :(得分:0)

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

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

同时将费用选择器更改为$('#cost')

答案 2 :(得分:0)

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

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