【问题标题】:JQuery - Multiply 3 input fields and auto populate the 4th inputJQuery - 将 3 个输入字段相乘并自动填充第 4 个输入
【发布时间】:2013-08-14 19:32:42
【问题描述】:

我有 3 个输入字段:

<input type="text" name="height" /> * <input type="text" name="width" /> *<input type="text" name="length" />
and the total:
= <input type="text" name="total" />

如何使用 jQuery 自动填充总字段?

谢谢!

【问题讨论】:

  • 您应该在任何输入字段的 onblur 或 onfocusout 函数上编写逻辑。检查@Sebastian 的答案
  • jsfiddle.net/cse_tushar/xZ3LM查看我的答案演示

标签: jquery


【解决方案1】:

首先,您应该在输入中添加 id:

<input type="text" id="txt1" ... /> 
// also for 2, 3 and 4 ...

然后,你可以简单地添加这个jquery事件来动态计算结果:

<script>
    $(document).ready(function () { 
        $("#txt1, #txt2, #txt3").change(function() {
            $("#txt4").val($("#txt1").val() * $("#txt2").val() * $("#txt3").val());
        });
    });
</script>

【讨论】:

    【解决方案2】:

    请看http://jsfiddle.net/uGgfh/

    $('.num').change(function(){
        var tot = 1;
        $.each($('input[class=num]'),function(){
          var curr_val = $(this).val();
            if(curr_val != ""){
              tot = tot * curr_val;
              $('.tot').val(tot);
            }
        });
    });
    

    【讨论】:

      【解决方案3】:

      将 id 添加到所有输入,然后 $('input#input4').val($('input#input1').val()*$('input#input2').val()*$('input#input3').val())

      【讨论】:

      • 您可以将 id 从输入中更改为您的姓名,例如 id="height", id="width".... 然后将 input1, input2... 更改为此 id 的
      • 谢谢,但它不会自动填充总字段。
      • 使用 if($('input#input1').val()!="" && $('input#input2').val()!=""...) { $ ('input#input4').val($('input#input1').val()*$('input#input2').val()*$('input#input3').val()) }
      【解决方案4】:

      DEMO

      $('input[type="text"]').keyup(function () {
          var result = 1;
          var x=0;
          $('input[type="text"]').not('input[type="text"][name=total]').each(function () {
              if (this.value != '') {
                  result *= this.value ;
                  x++;
              }
          });
          $('input[type="text"][name=total]').val((x == 0) ?0:result);
      });
      

      【讨论】:

        猜你喜欢
        • 2021-11-10
        • 1970-01-01
        • 2020-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-26
        • 2011-10-09
        • 1970-01-01
        相关资源
        最近更新 更多