如何使用jQuery动态计算佣金%?

时间:2015-04-27 07:43:01

标签: jquery dynamic

我想以asking价格计算12.5%佣金,并在用户输入时显示在commissiontotal下方。

<form action="">
    <label>Asking Price: <input type="number" id="asking" min="1" ></label><br>
    <input type="submit" value="Submit"><br>
    <span id="commission">Commission: </span>
    <span id="total">Total: </span><br>
</form>

到目前为止使用了这个

$( document ).ready(function() {
    var num = document.getElementById("asking").value;
    var comm = (num * 12.5)/100;
    num += comm;
    document.getElementById("commission").textContent=comm;
    document.getElementById("total").textContent=num;
});

3 个答案:

答案 0 :(得分:1)

$(document).ready(function(){
    $("#asking").keyup(function(){
        var asking = parseFloat($(this).val());
        var commission = asking * 0.125;

        $("#commission").text("Commission:"+ commission ); 
        $("#total").text("Total:"+( asking + commission ));   
    });    
});

答案 1 :(得分:1)

$(document).ready(function (){

$('#asking').change(function() {
    var $this = $(this);
    var currentValue = parseInt($this.val());
    var commission = currentValue * 0.125;
    var total = currentValue + commission;

    $('#commission').text('commission: ' + commission);
    $('#total').text('total: ' + total);
});
});

答案 2 :(得分:0)

您的代码几乎没有变化:

HTML:

<form action="">
    <label>Asking Price: <input type="number" id="asking" min="1" >        </label><br>
    <input type="submit" value="Submit"><br>
        <span id="commission">Commission: <span id="com"></span></span>
        <span id="total">Total: <span id="tot"></span></span><br>
</form>

使用Javascript:

$(document).ready(function () {
    $('#asking').on('change', function (e) {
        var value = parseInt($(this).val(), 10)
            commission = value * .125;

        $('#com').text(commission);
        $('#tot').text(value + commission);
    });
});

演示:https://jsfiddle.net/288a3o4d/