为什么 jQuery val() 返回空/对象

塞缪尔·阿索尔

我正在开发一种基于输入自动计算用户利润的表单。这是我的 html 表单:

$(document).ready(function() {
  $('#inv_amount').keyup(function() {
    var invAmount = $(this).val();
    var profit = $('#profitPercent').val();
    var profCalc = +invAmount + ((profit / 100) * invAmount);
    $('#exp_earning').val(profCalc);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <div class="form-group">
    <label for="inv_amount" class="control-label">Amount to Invest:</label>
    <input type="text" name="inv_amount" id="inv_amount" class="form-control" placeholder="Enter an amount" required="true">
  </div>
  <div class="form-group">
    <label for="exp_earning" class="control-label">Expected Earning:</label>
    <input type="text" name="exp_earning" id="exp_earning" class="form-control" placeholder="Your expected earning" disabled="true">
    <input type="hidden" name="profitPercent" id="profitPercent" value="12">
  </div>
</form>

编辑

利润计算正确,并显示在表格中,但当我检查表格时,exp_earning返回空。我还使用 console.log() 检查过,我发现它返回的是一个对象,而不是值。

另一个编辑:有两件事我真的很想知道。

  1. 为什么#exp_earning当我尝试提交表单时返回空,即使它在浏览器中可见。

  2. 当我尝试在浏览器控制台中使用 进行查看时,为什么该值显示为一个对象var outPut = $('#exp_earning').val(profCalc); console.log(outPut);

罗里·麦克罗森

问题是因为该#exp_earning字段上disabled设置属性。这意味着在提交表单时它将从请求中排除。

要解决此问题,只需删除该disabled属性即可。如果您不希望用户能够编辑该值,请readonly改用:

$(document).ready(function() {
  $('#inv_amount').keyup(function() {
    var invAmount = $(this).val();
    var profit = $('#profitPercent').val();
    var profCalc = +invAmount + ((profit / 100) * invAmount);
    $('#exp_earning').val(profCalc);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <div class="form-group">
    <label for="inv_amount" class="control-label">Amount to Invest:</label>
    <input type="text" name="inv_amount" id="inv_amount" class="form-control" placeholder="Enter an amount" required="true">
  </div>
  <div class="form-group">
    <label for="exp_earning" class="control-label">Expected Earning:</label>
    <input type="text" name="exp_earning" id="exp_earning" class="form-control" placeholder="Your expected earning" readonly="true">
    <input type="hidden" name="profitPercent" id="profitPercent" value="12">
  </div>
</form>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章