如何减去两个输入文本,如果在JQUERY中为负,则返回0

时间:2017-09-21 07:43:20

标签: javascript jquery html

如何减去两个输入文本并将其另外输入文本

这是我尝试但不工作的地方:

JQUERY:

$(".num3").on("keyup", function() {
 var $this = $(this).parent().parent();

    $this.find('.num1').val($this.find('.num3').val() - $this.find('.num2').val())

});

PHP / HTML:

<input type='text' name='num2' class='num2' value='". number_format((float)$try, 2, '.',''))."' autocomplete='off' readonly  >
<input type='text' name='num3' class='num3' autocomplete='off'>
<input type='text' name='num1' class='num1' readonly>

2 个答案:

答案 0 :(得分:0)

&#13;
&#13;
$(document).on('keyup', '.num3', function(){
    var num1 = !isNaN(parseInt($('.num3').val())) ? parseInt($('.num3').val()) : 0;
    var num2 = !isNaN(parseInt($('.num1').val())) ? parseInt($('.num1').val()) : 0;
    var sub = num1 - num2;
    sub = sub < 0 ? 0 : sub;
    $('.num2').val( sub )
})

$(document).on('keyup', '.num1', function(){
    var num1 = !isNaN(parseInt($('.num3').val())) ? parseInt($('.num3').val()) : 0;
    var num2 = !isNaN(parseInt($('.num1').val())) ? parseInt($('.num1').val()) : 0;
    var sub = num1 - num2;
    sub = sub < 0 ? 0 : sub;
    $('.num2').val( sub )
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' name='num2' class='num2' value='0' autocomplete='off' readonly  >

<input type='text' name='num3' class='num3' autocomplete='off'>

<input type='text' name='num1' class='num1' value="10">
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这很简单:

$(".num1").on("keyup", function() {
 var $this = $(this).parent().parent();
    var answer = $this.find('.num2').val() - $this.find('.num3').val();
    if(answer < 0)
    {
        $this.find('.num1').val(0);
    }
    else{
        $this.find('.num1').val(answer);
    }
});