-3

Hi I'm new for programming and I'm facing one problem.

I have 3 input for values and 1 input for total. What I need is when I change the value in any input total should change automatically.

<input type="text" name="Amt" id="amount" class="form-control" />
<input type="text" name="Amt" id="amount" class="form-control" />
<input type="text" name="Amt" id="amount" class="form-control" />

And for total I have:

<input type="text" class="form-control" name="total" id="total" value="" />

And below is the script:

<script type="text/javascript">
    $('#amount').change(function() {
        $('#total').attr('value', function() {
            var result = 0;
            $('#amount').each(function() {
                result += $(this).attr('value');
            });
            return result;
        });
    });
</script>
4

1 回答 1

0

您有多个 id amount。这些应该更改为类。此外,每个金额的值将被 jQuery 挑选为字符串,因此需要将其更改为整数:

$('.amount').change(function () {
  var result = 0;
  $('.amount').each(function () {
    result += +$(this).val();
  });
  $('#total').val(result);
});

小提琴

于 2013-11-14T10:40:55.793 回答