【问题标题】:jquery get values from a form field and do math with them function not workingjquery从表单字段中获取值并用它们做数学函数不起作用
【发布时间】:2014-11-24 07:28:35
【问题描述】:

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

jQuery:

    $('#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>

但这不起作用...有人可以帮我解决这个问题吗?

提前谢谢你!

【问题讨论】:

  • 而不是$('#numberOfItems').keyup尝试$(document).on('keyup','#numberOfItems',function(){})并使用paresInt(),如Satpal所示
  • 请也添加您的 html,以便我可以针对确切的问题制作一个 jsfiddle 并对其进行测试。
  • 另外,请告诉我们您的代码有哪些错误和问题。
  • 它没有显示任何错误......它根本不起作用!我提醒一些事情只是为了确保事件“keyup”被触发并且它确实触发了,但是我上面的代码只是没有用来自 totalweight 的值更改 div 的值

标签: javascript jquery forms function math


【解决方案1】:

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

 $('#numberOfItems').keyup(function(){

     $items = $('#numberOfItems').val();
     $weightitem = $('#weightitem').val();

     $totalweight = $items * $weightitem;

    $('#totalweight').val($totalweight);

});

【讨论】:

  • 只改变变量名并没有任何作用。如果您使用$.variable,您会将其设为 jquery 全局变量。但是只需添加$,您实际上只是更改了变量名。您的代码一定还有其他问题,您不小心更改了(可能只是变量名中的拼写错误)。
  • 另外,在这段代码的缩写形式中,您根本不需要单个变量名:$("#totalweight").val( $('#numberOfItems').val() * $('#weightitem').val() );
【解决方案2】:
<!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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-28
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多