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

时间:2017-06-14 08:26:08

标签: jquery

我正在处理一个表单,该表单根据输入自动计算用户的利润。这是我的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);在浏览器控制台中查看该值时,为什么该值显示为对象?

3 个答案:

答案 0 :(得分:2)

实际上你已禁用该字段。请删除disabled="true",然后尝试。

如果您希望该用户无法更改此字段,则可以添加属性readonly="readonly"

我希望这会对你有所帮助。

答案 1 :(得分:2)

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

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

&#13;
&#13;
$(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);
  });
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

如果你的意思是:

$('#exp_earning').val(profCalc);

...返回一个对象是预期的行为,如documented

  

.val( value )返回:jQuery

作为浏览器DOM检查器,它通常会显示实际的HTML属性,这些属性不一定反映DOM属性的值。

最后,disabled attribute阻止提交<input>(以及其他操作):

  

此布尔属性表示表单控件不可用于交互。特别是,不会在禁用的控件上调度click事件。此外,禁用控件的值不会以形式提交。

相关问题