jQuery从表单字段中获取值,并用它们做数学运算函数不起作用

jquery get values from a form field and do math with them function not working

本文关键字:不起作用 函数 运算 字段 表单 获取 jQuery      更新时间:2023-09-26

我在jquery中有一个函数,在keyup上,它应该对来自2个字段的值进行数学运算,并使用总权重ID更改我的总权重字段的值,如下所示:

j查询:

    $('#numberOfItems').keyup(function(){
        var items = $('#numberOfItems').val();
        var weightitem = $('#weightitem').val();
        var totalweight = items * weightitem;
        $('#totalweight').val(totalweight);
    });

.HTML:

<div>
<form>
   <input type="text" id=weightitem"" placeholder="Weight per item">
   <input type="text" id=numberOfItems"" placeholder="Items">
   <input type="text" id=totalweight"" placeholder="Weight in total">
</form>
</div>

但这行不通...谁能帮我解决这个问题?

提前谢谢你!

我以前遇到过同样的问题,但我不明白为什么会发生这种情况。但是我已经通过使用 $ 符号而不是 var 声明变量来解决它。

 $('#numberOfItems').keyup(function(){
     $items = $('#numberOfItems').val();
     $weightitem = $('#weightitem').val();
     $totalweight = $items * $weightitem;
    $('#totalweight').val($totalweight);
});
<!doctype html>
<html lang="en">    
<head>
  <meta charset="utf-8">
  <title>Hide</title>
  <script src="http://code.jquery.com/jquery-1.10.2.js"></script>  
  <style type="text/css">
  label input[type="file"] 
{
display: block;
margin-top: -20px;
opacity: 0;
}
  </style>
  <script>
  var items=0;
  var weightitem=0;
  var totalweight=0;
  $('#numberOfItems').keyup(function(){
        var items = $('#numberOfItems').val();
        var weightitem = $('#weightitem').val();
        var totalweight = items * weightitem;
        $('#totalweight').val(totalweight);
    });
   $(window).ready(function() {
$(document).delegate('#numberOfItems','keyup',function(){
  items = $(this).val();
  weightitem = $('#weightitem').val();
  totalweight = items * weightitem;
  $('#totalweight').val(totalweight);
});
$(document).delegate('#weightitem','keyup',function(){
  items = $('#numberOfItems').val();
  weightitem = $(this).val();
  totalweight = items * weightitem;
  $('#totalweight').val(totalweight);
});
});
  </script>
</head>
<body>
<input type='text' id='numberOfItems'>
<input type='text' id='weightitem'>
<input type='text' id='totalweight'>
</body>
</html>