Javascript函数未在所需字段中提供算术值

我正在以HTML格式使用Javascript实现简单的算术运算符功能。但这是行不通的。看起来不错,但是不知道为什么它没有在期望的字段中显示价值。请看一下我的以下代码和指南。

var input = $('[name="ServiceTotalCost"],[name="GrantRequest"],[name="MatchingShare"]'),
  ServiceTotalCost = $('[name="ServiceTotalCost"]'),
  GrantRequest = $('[name="GrantRequest"]'),
  MatchingShare = $('[name="MatchingShare"]');

input.change(function() {
  var ServiceTotalCost = (isNaN(parseInt(ServiceTotalCost.val()))) ? 0 : parseInt(ServiceTotalCost.val());
  var GrantRequest = (isNaN(parseInt(GrantRequest.val()))) ? 0 : parseInt(GrantRequest.val());

  if (ServiceTotalCost > GrantRequest) {
    Difference = ServiceTotalCost - GrantRequest;
    MatchingShare.val(Difference);
  } else if (GrantRequest >= ServiceTotalCost) {
    PercentAge = (GrantRequest * 20) / 100;
    MatchingShare.val(PercentAge);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-12">
  <div class="form-group form-float">
    <h2>*Support Requried Through Grant</h2><br>
    <div class="form-line">
      <input type="number" class="form-control" name="ServiceTotalCost" id="ServiceTotalCost" required>
      <label class="form-label">Total cost of the service (Rs.)</label>
    </div>
  </div>
</div>
<div class="col-md-12">
  <div class="form-group form-float">
    <div class="form-line">
      <input type="number" class="form-control" name="GrantRequest" max="500000" id="GrantRequest" required>
      <label class="form-label">Amount of grant requested (Rs.)*</label>
    </div>
  </div>
</div>
<div class="col-md-12">
  <div class="form-group form-float">
    <div class="form-line">
      <input type="number" name="MatchingShare" id="MatchingShare" class="form-control" readonly>
      <label class="form-label">Matching share by the applicant (Rs.)</label>
    </div>
  </div>
</div>
评论
  • jquia
    jquia 回复

    您正在控制台中获得此信息:

    未捕获的TypeError:无法读取未定义的属性“ val”

    The reason is things like this in the change handler:

    var ServiceTotalCost = (isNaN(parseInt(ServiceTotalCost.val()))) ? 0 : parseInt(ServiceTotalCost.val());
    

    That creates a local ServiceTotalCost variable that initially has the value undefined, and then in its initializer tries to use it as an object. (I assume you meant to use the ServiceTotalCost from outside the function, but the local shadows it, making it inaccesible.)

    为处理程序关闭的变量(为包含字段的jQuery对象的变量)赋予本地名称不同的名称。