修复返回错误的输出

时间:2018-11-26 10:14:13

标签: javascript jquery

function get_tax(rent) {
    var pcharges = parseFloat($('#pcharges').val());
    pcharges = pcharges.toFixed(2);
    rent = parseFloat(rent);
    rent = rent.toFixed(2);

    var tax = parseFloat((rent * 15) / 100);
    tax = tax.toFixed(2);

    $('#tax').val(tax);
    var tot_rent = pcharges + rent + tax;
    // alert(tot_rent);
    $('#tot_rent').val(tot_rent);
    // alert(tax);

}

function get_total(pcharges) {
    pcharges = parseFloat(pcharges);
    old_tot = parseFloat($('#tot_rent').val());
    // alert(pcharges+old_tot);
    $('#tot_rent').val(pcharges + old_tot);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Rent:<input required onkeyup="this.value=this.value.replace(/[^0-9.]/g,'');" onchange="get_tax(this.value)" type="text" name="rent">
Tax:<input required onkeyup="this.value=this.value.replace(/[^0-9.]/g,'');" id="tax" type="text" name="tax">
Phone Charges:<input value="0" onkeyup="this.value=this.value.replace(/[^0-9.]/g,'');" required id="pcharges"  onchange="get_total(this.value)" type="text" name="pcharges">
Total Rent:<input required onkeyup="this.value=this.value.replace(/[^0-9.]/g,'');" id="tot_rent" type="text" name="tot_rent">

我想从用户那里获得租金并在税中显示15%,用户将手动放置电话费用,然后我需要添加租金,税金,电话费用。税收适当,但租金总额不适当

2 个答案:

答案 0 :(得分:1)

您正在尝试添加要连接值的字符串值(toFixed()返回字符串),使用一元加号(+)转换为浮点数,然后执行加法。

function get_tax(rent) {
    var pcharges = parseFloat($('#pcharges').val());
    pcharges = +pcharges.toFixed(2);
    rent = parseFloat(rent);
    rent = +rent.toFixed(2);

    var tax = parseFloat((rent * 15) / 100);
    tax = +tax.toFixed(2);

    $('#tax').val(tax);
    var tot_rent = pcharges + rent + tax;
    // alert(tot_rent);
    $('#tot_rent').val(tot_rent);
    // alert(tax);

}

function get_total(pcharges) {
    pcharges = parseFloat(pcharges);
    old_tot = parseFloat($('#tot_rent').val());
    // alert(pcharges+old_tot);
    $('#tot_rent').val(pcharges + old_tot);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Rent:<input required onkeyup="this.value=this.value.replace(/[^0-9.]/g,'');" onchange="get_tax(this.value)" type="text" name="rent">
Tax:<input required onkeyup="this.value=this.value.replace(/[^0-9.]/g,'');" id="tax" type="text" name="tax">
Phone Charges:<input value="0" onkeyup="this.value=this.value.replace(/[^0-9.]/g,'');" required id="pcharges"  onchange="get_total(this.value)" type="text" name="pcharges">
Total Rent:<input required onkeyup="this.value=this.value.replace(/[^0-9.]/g,'');" id="tot_rent" type="text" name="tot_rent">

答案 1 :(得分:1)

这是因为.toFixed()返回string值。因此,如果您添加多个string值,它将串联起来

更改

 var tot_rent = pcharges + rent + tax;

收件人

var tot_rent = var tot_rent = parseFloat( pcharges) + parseFloat(rent) + parseFloat(tax);

DEMO HERE