尝试实时更新2个输入字段的计算

时间:2014-08-25 05:30:30

标签: javascript jquery

我正在尝试计算2个输入字段并在div totalPrice中实时显示结果 无论我尝试过什么都无法让它发挥作用

thx

<script src="jquery-1.11.1.min.js">
    jQuery('#field2').on('input propertychange paste', function() {
        var op1 = document.getElementById('field1');
        var op2 = document.getElementById('field2');
        var result = document.getElementById('totalPrice');
        if (op1.value == "" || op1.value != parseFloat(op1.value)) op1.value = 0;
        if (op2.value == "" || op2.value != parseFloat(op2.value)) op2.value = 0;
        result.value = 0;
        result.value = parseInt(result.value);
        result.value = parseInt(result.value) + parseInt(op1.value) + parseInt(op2.value);
    }
    var divobj = document.getElementById('totalPrice'); divobj.style.display = 'block'; divobj.innerHTML = "Total $" + result.value;
    });
</script>
<form action="" id="cakeform" onsubmit="return false;">
    <input type="text" value="" size="20" name="field1" id="field1" class="rsform-input-box">
    <input type="text" value="" size="20" name="field2" id="field2" class="rsform-input-box">
    <div id="totalPrice"></div>
</form>

2 个答案:

答案 0 :(得分:2)

这个http://jsfiddle.net/20Lgz8ey/2/

怎么样?
 $('#field1,#field2').on('input propertychange paste', function() {


     $('#totalPrice').html(parseFloat($("#field1").val()!=''?$("#field1").val():0)+parseFloat($("#field2").val()!=''?$("#field2").val():0));
    });

<script src="jquery-1.11.1.min.js"></script>
<script>
   code ....
</script>

答案 1 :(得分:0)

    $(document).ready(function () {
        jQuery('#field2, #field1').on('input propertychange paste', function () {
            var op1 = document.getElementById('field1');
            var op2 = document.getElementById('field2');
            var result = document.getElementById('totalPrice');
            if (op1.value == "" || op1.value != parseFloat(op1.value)) op1.value = 0;
            if (op2.value == "" || op2.value != parseFloat(op2.value)) op2.value = 0;
            result.value = 0;
            result.value = parseInt(result.value);
            result.value = parseInt(result.value) + parseInt(op1.value) + parseInt(op2.value);
            var divobj = document.getElementById('totalPrice'); divobj.style.display = 'block'; divobj.innerHTML = "Total $" + result.value;
        })            
    });

尝试这个,如果它可以帮助你。