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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19571718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:01:03  来源:igfitidea点击:

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

javascriptjqueryforms

提问by facemoi

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...

我知道这是一个非常基本的问题,但我坚持这一点。我有两个输入框,我想计算这些输入并立即将结果显示到另一个输入(第三个)中,而无需提交按钮。我的意思是,一旦我开始将值输入到输入中,结果将实时显示在第三个输入中,它代表结果......

<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>

回答by Artem Fitiskin

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/

回答by Fallenreaper

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);
}

回答by Vinay Pratap Singh

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

现场演示

回答by Arun

 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);     
 }