简体   繁体   English

如何计算两个输入表单字段并将值放入另一个而不使用jquery提交表单?

[英]How to calculate two input form fields and put the value in another without submitting the form using jquery?

I know this is an extremely basic question but I'm stuck on this. 我知道这是一个非常基本的问题,但我坚持这个。 I have two input boxes and I want to calculate those inputs and show the result into another input (3rd one) immediately without the need of a submit button. 我有两个输入框,我想计算这些输入,并立即将结果显示到另一个输入(第三个),而无需提交按钮。 I means, once I start entering the values into the input and the result will shows live in the 3rd input which is the represent the result... 我的意思是,一旦我开始将值输入到输入中,结果将显示在第3个输入中,它代表结果...

<input type="text" class="input value1">
<input type="text" class="input value2">
<input type="text" disabled="disabled" id="result">

<script>
 $(document).ready(function(){
      var val1 = $(".value1").val();
      var val2 = $(".value2").val();
      $(".input").keyup(function(){
         $("#result").text(val1+val2);
       });
});
</script>

Put val1 and val2 in keyup statement. 将val1和val2放在keyup语句中。

$(document).ready(function(){
    $(".input").keyup(function(){
          var val1 = +$(".value1").val();
          var val2 = +$(".value2").val();
          $("#result").val(val1+val2);
    });
});

Look at fiddle: http://jsfiddle.net/g7zz6/ 看小提琴: http//jsfiddle.net/g7zz6/

Under the assumption of SUM as you stated, the inputs will be numberic in nature. 根据您所说的SUM假设,输入本质上是数字的。

$(".input").on("change", function(){
    var ret = Number($(".value1").val()) + Number($(".value2").val());
    $("#result").val(ret);
}

just set the text value, also you need to parse them as other wise they will be concatenated as strings. 只需设置文本值,你也需要解析它们,因为它们将被串联为字符串。

$(document).ready(function () {
    var val = parseInt($(".value1").val()) + parseInt($(".value2").val());
    $("#result").text(val);
});

Live Demo 现场演示

 function addinput(){ 
   var x= Number(document.getElementById("first").value);
   var y= Number(document.getElementById("second").value);
   var z= Number(x+y);
   document.getElementById("l").value = Number(z);     
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM